get the miniumum value in pandas vectorization

Question:

I’m creating a column which is based on 2 other columns but also has an extra condition:

df['C'] = min((df['B'] - df['A']) , 0)

The new column is the subtraction of A and B, but if the value is negative it has to be 0. The above function does not work unfortunately. Can anyone help?

Asked By: borisvanax

||

Answers:

Use np.maximum:

df['C'] = np.maximum((df['B'] - df['A']) , 0)
Answered By: jezrael

You could use df.clip to set a lower bound for the data (i.e. any data below 0 to show as 0):

df['C'] = (df['B'] - df['A']).clip(lower=0)

Note: If you don’t want any negatives, your original idea should use max rather than min. A negative would be < 0, it would keep the negative. You’d end up replacing all positive numbers with 0 rather than the negatives (e.g. min(-5, 0) would output -5)

Answered By: Emi OB
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.