pandas apply function on column only if condition on another column is met

Question:

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?

Asked By: okuoub

||

Answers:

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
Answered By: jezrael

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

df['val'] -= 0.1*(~df['cond'])*(df['val'] > 0.55)
Answered By: Swifty

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
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.