LMGagne
LMGagne

Reputation: 1716

Replace values in one column with another column values on conditions

I have a df that looks like this

ID num1       children num2
34 self       1        1
23 none       2        0
85 dependents 3        2

I'd like to replace the values in num2 with the values from children only if num1 = 'dependents'. I've tried a handful of things including mask but haven't been able to get it to work

mask = (df['num1'] == 2)
df['num1'][mask] = df['children']

ideally the output looks like this

ID num1       children num2
34 self       1        1
23 none       2        0
85 dependents 3        3

Upvotes: 1

Views: 46

Answers (1)

ansev
ansev

Reputation: 30920

Use 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'])

or DataFrame.loc:

df.loc[cond,'num2'] = df['children']

Output

   ID        num1  children  num2
0  34        self         1     1
1  23        none         2     0
2  85  dependents         3     3

Detail

print(cond)
0    False
1    False
2     True
Name: num1, dtype: bool

Upvotes: 3

Related Questions