I have a DataFrame df
:
A B
a 2 2
b 3 1
c 1 3
I want to create a new column based on the following criteria:
if row A == B: 0
if rowA > B: 1
if row A < B: -1
so given the above table, it should be:
A B C
a 2 2 0
b 3 1 1
c 1 3 -1
For typical if else
cases I do np.where(df.A > df.B, 1, -1)
, does pandas provide a special syntax for solving my problem with one step (without the necessity of creating 3 new columns and then combining the result)?
df['C']=df.apply(myFunc(row), axis=1)
where myFunc does what you want, this does not involve creating '3 columns' – Dwaindwainecase_when
(a syntax useful in SQL in the context in the OP). See this answer for a demo. – Melendez