Modify a subset of a pandas column using data from another column

Viewed 106

I am trying to modify specific values in a column, where the modification uses values from another column. For example say I have a df:

A    B    C
1    3    8
1    6    8
2    2    9
2    6    1
3    4    5
3    6    7

Where I want df['B'] = df['B'] + df['C'] only for the subset df.loc[df['A'] == 2]

Producing:

A    B    C
1    3    8
1    6    8
2    11   9
2    7    1
3    4    5
3    6    7

I have tried

df.loc[(df['A']==2), 'B'].apply(lambda x: x + df['C'])

but get:

InvalidIndexError: Reindexing only valid with uniquely valued Index objects

2 Answers

You are close, apply is not necessary:

m = df['A'] == 2
#short way
df.loc[m, 'B'] += df.loc[m, 'C']
#long way
df.loc[m, 'B'] = df.loc[m, 'B'] + df.loc[m, 'C']

Or:

df.loc[df['A'] == 2, 'B'] += df['C']

If you don't mind using numpy, I find it very simple for tasks like yours:

import numpy as np
df['B'] =  np.where(df['A'] == 2, df['B']+df['C'],df['B'])

prints:

   A   B  C
0  1   3  8
1  1   6  8
2  2  11  9
3  2   7  1
4  3   4  5
5  3   6  7
Related