You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Python表格小数值乘1000转换后部分行出现异常超大值问题求助

Fixing Your Excel Decimal-to-Integer Conversion Issues

Okay, let's break down exactly what's causing those weird oversized values and fix your script step by step.

1. The Root Cause of Your "Super Large Value" Problem

Your current loop for converting decimals to integers is using replace incorrectly:

for i in range(8):
    print(table2[1][i])
    valor2 = int(table2[1][i] * 1000)
    table2[1] = table2[1].replace(table2[1][i], valor2)

When you call table2[1].replace(old_value, new_value), it replaces every occurrence of old_value in the entire column—not just the row at index i. Here's what happens:

  • Suppose row 0 has a value of 0.1: you convert it to 100 and replace all 0.1 in the column with 100.
  • Later, when you get to row 5 which originally had 0.1, the value in table2[1][5] is now 100 (from the first replace). You multiply that by 1000 to get 100000, then replace all 100 values in the column with 100000—including row 0's correct 100.
  • This chain reaction creates those massive incorrect values you're seeing.

2. Secondary Issue: Inefficient (and Risky) Empty Row Removal

Your loop to delete empty rows is error-prone because dropping rows shifts the index, but you're still iterating over the original range of indices. This can lead to skipping rows or trying to access indices that no longer exist.

3. Fixed Code with Explanations

Here's the revised script that addresses both problems:

import pandas as pd
import numpy as np  # For safer rounding to avoid floating-point precision issues

def DESTINOS_CLUBE_CLIENTE_MOD072():
    # Load Excel sheet
    table = pd.read_excel('./planilha.xlsx', sheet_name='LP')
    
    # Replace your manual row-deletion loop with this pandas-native method
    # Drops rows where column 1 has NaN values
    table = table.dropna(subset=[1])
    table.reset_index(inplace=True, drop=True)
    
    # No need to create a copy with pd.DataFrame(table) since table is already a DataFrame
    table2 = table.copy()
    table2.reset_index(inplace=True, drop=True)
    
    # Fix the decimal-to-integer conversion: apply to the entire column at once
    # Use np.rint to handle floating-point precision quirks (e.g., 0.1*1000 = 99.9999999999 instead of 100)
    table2[1] = np.rint(table2[1] * 1000).astype(int)
    
    # Optional: Verify the first 8 values to confirm correctness
    print("First 8 converted values:")
    print(table2[1].head(8))
    print("\nFull processed table:")
    print(table2)
    
    # Rest of your code for generating the JS snippet remains mostly the same
    oneCard = ""
    for i in range(table2.shape[0]):
        values = 'element{}.querySelector("{}").value="{}"; element{}.querySelector("{}").value="{}"; element{}.querySelector("{}").value="{}"; element{}.querySelector("{}").value="{}"; element{}.querySelector("{}").value="{}";' . format(
            i, "input[name*='Origem']", table2['ORIGEM'][i],
            i, "input[name*='Destino']", table2['DESTINOS'][i],
            i, "input[name*='Clube_valor']", table2[1][i],
            i, "input[name*='Geral_valor']", table2['1.1'][i],
            i, "input[name*='Link_botao']", table2['LINKS'][i]
        )
        oneCard += f" let element{i} = document.querySelectorAll('[data-fieldname=Itens]')[{i}]; setTimeout(()=>{{{values}}},10000);"
    
    cod = f"let totalElements = document.querySelectorAll('[data-fieldname=Itens]').length == {table2.shape[0]} ? 0 : {table2.shape[0]} - document.querySelectorAll('[data-fieldname=Itens]').length; let element = document.querySelector('[data-fieldname=Itens]'); for(i = 0; i < totalElements; i++){{element.children[13].click()}} setTimeout(() => {{{oneCard}}}, 10000); setTimeout(() => {{console.log('Pronto, pode publicar!')}}, 20050);"
    
    # Assuming your file() and message() functions are defined elsewhere
    file(cod)
    message()

DESTINOS_CLUBE_CLIENTE_MOD072()

Key Improvements:

  • Column-wide conversion: Instead of looping and replacing, we convert the entire column in one go with np.rint(table2[1] * 1000).astype(int). This avoids accidental mass-replacement of values.
  • Floating-point precision handling: np.rint() rounds to the nearest integer, which fixes cases where decimal multiplication leads to tiny off-by-one errors (like 0.001 * 1000 = 0.9999999999 instead of 1).
  • Safer empty row removal: dropna(subset=[1]) directly removes all rows with missing values in column 1, no risky loops involved.
  • Cleaner string formatting: Used f-strings for the JavaScript code to make it more readable.

Test this out, and you should see those oversized values disappear—all your decimals will be correctly converted to integers without unintended side effects.

内容的提问来源于stack exchange,提问作者Bjorn Ruiz

火山引擎 最新活动