Home > other >  Performing calculation on multiple columns with the same condition
Performing calculation on multiple columns with the same condition

Time:06-14

I have the following DataFrame:

df = pd.DataFrame([[1,2,3],
                   [-1,3,2],
                   [3,4,5],
                   [-3,4,5]], columns=['A','B','C'])
condition = df['A']>0
df.loc[condition, 'B'] = df['B']   1
df.loc[condition, 'C'] = df['C'] * 2
print(df.head())

I am performing two different operations on two columns based on the same condition. What is the best way to group these two lines of code into a one liner?

df.loc[condition, 'B'] = df['B']   1
df.loc[condition, 'C'] = df['C'] * 2

CodePudding user response:

Use concat by both Series, because different operations:

df.loc[condition, ['B','C']] = pd.concat([df['B']   1, df['C'] * 2], axis=1)
print(df)
   A  B   C
0  1  3   6
1 -1  3   2
2  3  5  10
3 -3  4   5

In my opinion 2 rows are more readable:

df.loc[condition, 'B']  = 1
df.loc[condition, 'C'] *= 2

CodePudding user response:

One option is with assign:

df.assign(B = df.B.mask(condition, df.B   1), 
          C = df.C.mask(condition, df.C * 2))
Out[298]:
   A  B   C
0  1  3   6
1 -1  3   2
2  3  5  10
3 -3  4   5
  • Related