You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:利用循环替换DataFrame列中的指定0值

How to Replace 0 Values in a DataFrame Column with Corresponding List Values in a Loop?

Problem Breakdown

Your current code has a few key issues that are preventing the correct replacement:

  1. When using inplace=True, the replace() method returns None—assigning this back to result will overwrite your DataFrame with a None value, which breaks your data.
  2. You're targeting the string '0', but your DataFrame contains numeric 0 values, so the match won't work.
  3. You haven't tied the loop logic to the specific rows that should get each replacement value from your contas list.

Solution

Based on your description, it sounds like you want to replace 0 values in the Contas Resultado column with the corresponding financial metric from your contas list (e.g., replace 0 in rows associated with "Faturamento" with "Faturamento"). Here's the corrected approach:

contas = ["Margem Bruta","Faturamento", "Resultado Bruto", "Resultado Líquido", "Despesas Operacionais", "Despesas Vendas"]
results = []

# Assume your initial query result is stored in this DataFrame
df = ... # Your query-generated DataFrame

for conta in contas:
    # Create a mask to target rows where:
    # 1. The Contas column matches the current metric
    # 2. Contas Resultado is 0
    target_rows = (df['Contas'] == conta) & (df['Contas Resultado'] == 0)
    # Replace the 0 values with the current metric name
    df.loc[target_rows, 'Contas Resultado'] = conta

# Add the processed DataFrame to your results list
results.append(df)

Key Notes

  • Using .loc for conditional assignment is the safest way to modify DataFrames in Pandas, avoiding chained assignment warnings.
  • We're matching numeric 0 instead of the string '0' to ensure we target the correct rows.
  • The loop ensures each metric from contas only affects rows associated with that metric, keeping your replacements aligned with your data structure.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:03:03