我有一个看起来像这样的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

最佳答案

使用Series.where / Series.mask

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

09-25 20:40