Skip to content Skip to sidebar Skip to footer

Pandas: Search And Add Values To Cells Of Multiple Column

Suppose I search a dataframe like this df[df['a'] > 5] and then I want to add 5 and 10 respectively to column b and c of the search result. For example, a b c 7 2 5 3 4

Solution 1:

One-liner that will do the trick:

df.loc[df.a > 5, ['b', 'c']] += (5, 10)

Solution 2:

You can do this using np.where:

In[223]:
(df['b'],df['c']) = np.where(df['a'] > 5, (df['b'] + 5, df['c'] + 10), (df['b'],df['c']))
df

Out[223]: 
   a  b   c
0  7  7  15
1  3  4   7
2  6  6  13

Here we pass the boolean condition as the first arg df['a'] > 5, when True it returns a tuple of the cols of interest with the scalar value added, when False it returns the original df, the trick here is to construct a tuple of the different operations so we can perform 2 distinct operations and assign these to a tuple of the same cols

Solution 3:

You can simply use loc like this:

df.loc[df['a']>5,'b'] +=5
df.loc[df['a']>5,'c'] += 10

Post a Comment for "Pandas: Search And Add Values To Cells Of Multiple Column"