多条件修改DataFrame列值求助:无法实现指定条件字段替换
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

