我有一个看起来像这样的df
ID num1 children num2
34 self 1 1
23 none 2 0
85 dependents 3 2
仅当
num2
='depends'时,我才想用children
中的值替换num1
中的值。我已经尝试了包括mask
在内的一些方法,但未能使其正常工作mask = (df['num1'] == 2)
df['num1'][mask] = df['children']
理想情况下,输出看起来像这样
ID num1 children num2
34 self 1 1
23 none 2 0
85 dependents 3 3
最佳答案
cond = df['num1'].eq('dependents')
df['num2'] = df['num2'].mask(cond,df['children'])
#df['num2'] = df['children'].where(cond,df['num2'])
或
DataFrame.loc
:df.loc[cond,'num2'] = df['children']
输出量
ID num1 children num2
0 34 self 1 1
1 23 none 2 0
2 85 dependents 3 3
详情
print(cond)
0 False
1 False
2 True
Name: num1, dtype: bool