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

多条件修改DataFrame列值求助:无法实现指定条件字段替换

Fixing Conditional Value Updates in pandas

Hey there! Let's sort out this pandas value update issue you're facing. The problem with your original code is that you're replacing entire rows matching your conditions instead of just targeting the tabela_qar.resposta column. Here's how to fix it:

Correct Approach: Target Only the Resposta Column

Instead of assigning the entire str.replace result to the filtered rows, specify the exact column you want to modify in your .loc call:

# Update only the resposta column where conditions are met
df.loc[
    (df['tabela_qar.pergunta'] == 'POSSUI GARAGEM NO LOCAL DE TRABALHO') & 
    (df['tabela_qar.resposta'] == 'NÃO'),
    'tabela_qar.resposta'  # This tells pandas to only update this column
] = 'GARAGEM TRABALHO'

Why Your Original Code Failed

Your original line:

df.loc[(df['tabela_qar.resposta']=='NÃO') & (df['tabela_qar.pergunta']=='POSSUI GARAGEM NO LOCAL DE TRABALHO')] = df['tabela_qar.resposta'].str.replace('NÃO','GARAGEM TRABALHO')

This replaces every column in the matching rows with the full str.replace series (which includes values from non-matching rows too). By adding the column name as the second argument to .loc, you restrict the update to only the resposta column.

Handling Multiple Conditions (Optional)

If you have several condition-value pairs to apply, using numpy.select makes it cleaner:

import numpy as np

# Define your condition-value pairs
conditions = [
    (df['tabela_qar.pergunta'] == 'POSSUI GARAGEM NO LOCAL DE TRABALHO') & (df['tabela_qar.resposta'] == 'NÃO'),
    (df['tabela_qar.pergunta'] == 'POSSUI ESTACIONAMENTO PÚBLICO') & (df['tabela_qar.resposta'] == 'SIM'),
    # Add more conditions here
]

values = [
    'GARAGEM TRABALHO',
    'ESTACIONAMENTO PUBLICO',
    # Corresponding values for each condition
]

# Apply the updates, keeping original values where no conditions match
df['tabela_qar.resposta'] = np.select(conditions, values, default=df['tabela_qar.resposta'])

Verify the Changes

After running the code, confirm the updates worked with your value_counts() check:

print(df['tabela_qar.resposta'].value_counts())

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:34:38