2

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

2 Answers 2

2

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))
Sign up to request clarification or add additional context in comments.

2 Comments

I was used to doing the following (create a two category c variable based on another variable): df['c'] = df['a'].map(lambda x: 0 if x>5 else 1) can I do something similar using one variable?
Yes but I wouldn’t advise it
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.