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:
- When using
inplace=True, thereplace()method returnsNone—assigning this back toresultwill overwrite your DataFrame with aNonevalue, which breaks your data. - You're targeting the string
'0', but your DataFrame contains numeric0values, so the match won't work. - You haven't tied the loop logic to the specific rows that should get each replacement value from your
contaslist.
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
.locfor conditional assignment is the safest way to modify DataFrames in Pandas, avoiding chained assignment warnings. - We're matching numeric
0instead of the string'0'to ensure we target the correct rows. - The loop ensures each metric from
contasonly affects rows associated with that metric, keeping your replacements aligned with your data structure.
内容的提问来源于stack exchange,提问作者Cesar
相关产品推荐
相关产品推荐

