Using lambda if condition on different columns in Pandas dataframe Using lambda if condition on different columns in Pandas dataframe numpy numpy

Using lambda if condition on different columns in Pandas dataframe


is that what you want?

In [300]: frame[['b','c']].apply(lambda x: x['c'] if x['c']>0 else x['b'], axis=1)Out[300]:0   -1.0998911    0.5828152    0.9015913    0.900856dtype: float64


Solution

use a vectorized approach

frame['d'] = frame.b + (frame.c > 0) * (frame.c - frame.b)

Explanation

This is derived from the sum of

(frame.c > 0) * frame.c  # frame.c if positive

Plus

(frame.c <= 0) * frame.b  # frame.b if c is not positive

However

(frame.c <=0 )

is equivalent to

(1 - frame.c > 0)

and when combined you get

frame['d'] = frame.b + (frame.c > 0) * (frame.c - frame.b)