Home > OS >  pandas apply function on column only if condition on another column is met
pandas apply function on column only if condition on another column is met

Time:12-16

I have a dataframe:

df =  A. Cond Val
      1. True 0.8
      5. False 0.8
      2. False 0.6
      4. False 0.5

I want to update the value of the columns 'Val' by truncate it in 0.1, only when Cond is False and val is higher than 0.55. So new df will be:

df =  A. Cond Val
      1. True 0.8
      5. False 0.7
      2. False 0.5
      2. False 0.5

What is the best way to do it?

CodePudding user response:

Use boolean indexing with DataFrame.loc, for test False values invert maks by ~ and chain another mask by Series.gt:

df.loc[df['Val'].gt(0.55) & ~df['Cond'], 'Val'] -= 0.1
print (df)
    A.   Cond  Val
0  1.0   True  0.8
1  5.0  False  0.7
2  2.0  False  0.5
3  4.0  False  0.5

CodePudding user response:

Use boolean indexing with two conditions and AND (&):

df.loc[df['Val'].gt(0.55) & ~df['Cond'], 'Val'] -= 0.1

Output:

    A.   Cond  Val
0  1.0   True  0.8
1  5.0  False  0.7
2  2.0  False  0.5
3  4.0  False  0.5

Conditions:

    A.   Cond  Val  df['Val'].gt(0.55)  ~df['Cond']    AND
0  1.0   True  0.8                True        False  False
1  5.0  False  0.8                True         True   True
2  2.0  False  0.6                True         True   True
3  4.0  False  0.5               False         True  False

CodePudding user response:

Using the int values of booleans, this would work too:

df['val'] -= 0.1*(~df['cond'])*(df['val'] > 0.55)
  • Related