Bebio
Bebio

Reputation: 409

Maximum of calculated pandas column and 0

I have a very simple problem (I guess) but don't find the right syntax to do it :

The following Dataframe :

   A   B  C
0  7  12  2
1  5   4  4
2  4   8  2
3  9   2  3

I need to create a new column D equal for each row to max (0 ; A-B+C)

I tried a np.maximum(df.A-df.B+df.C,0) but it doesn't match and give me the maximum value of the calculated column for each row (= 10 in the example).

Finally, I would like to obtain the DF below :

  A   B  C   D
0  7  12  2   0
1  5   4  4   5
2  4   8  2   0
3  9   2  3  10 

Any help appreciated Thanks

Upvotes: 1

Views: 645

Answers (3)

BENY
BENY

Reputation: 323316

Let us try

df['D'] = df.eval('A-B+C').clip(lower=0)
Out[256]: 
0     0
1     5
2     0
3    10
dtype: int64

Upvotes: 2

maow
maow

Reputation: 2887

To do this in one line you can use apply to apply the maximum function to each row seperately.

In [19]: df['D'] = df.apply(lambda s: max(s['A'] - s['B'] + s['C'], 0), axis=1)                                                                                                                            

In [20]: df                                                                                                                                                                                                
Out[20]: 
   A  B  C   D
0  0  0  0   0
1  5  4  4   5
2  0  0  0   0
3  9  2  3  10

Upvotes: 0

Henry Yik
Henry Yik

Reputation: 22503

You can use np.where:

s = df["A"]-df["B"]+df["C"]
df["D"] = np.where(s>0, s, 0) #or s.where(s>0, 0)

print (df)

   A   B  C   D
0  7  12  2   0
1  5   4  4   5
2  4   8  2   0
3  9   2  3  10

Upvotes: 0

Related Questions