RJL
RJL

Reputation: 351

Using lambda to create a new variable in Pandas

if I want to do the following in Pandas, how do I do it using Lambda:

df['c'] = 0
df['c'][(df['a']==1) | (df['b'] ==1)] = 1

Thanks

Upvotes: 2

Views: 486

Answers (2)

Jt Miclat
Jt Miclat

Reputation: 144

You can use apply but change the axis.

import pandas as pd

df =pd.DataFrame({'a':[1,2], 'b':[1,2]})
df['c'] = df.apply(lambda df: 1 if(df['a'] == 1| df['b']==1) else 0, axis = 1)

Upvotes: 1

piRSquared
piRSquared

Reputation: 294218

I can't justify using a lambda

df.assign(c=df[['a', 'b']].eq(1).any(1).astype(int))

But if you insist:

df.assign(c=lambda d: d[['a', 'b']].eq(1).any(1).astype(int))

Upvotes: 2

Related Questions