Tie_24
Tie_24

Reputation: 647

New column based in multiple conditions

     a    b
0  100   90
1   30  117
2   90   99
3  200   94

I want to create a new df["c"] with next conditions:

Output should be:

     a    b    c
0  100   90  100
1   30  117   30
2   90   99   90
3  200   94   94

I´ve tried:

df['c'] = np.where(df.eval("0.5 * a <= b <= 1.5 * a"), df.a, df.b)

But I don´t know how to include the last condition (If a <= 50, then c = a) in this sentence.

Upvotes: 2

Views: 70

Answers (1)

cs95
cs95

Reputation: 402333

You're almost there, you'll just need to add an or clause inside your eval string.

np.where(df.eval("(0.5 * a <= b <= 1.5 * a) or (a <= 50)"), df.a, df.b)
#                                           ~~~~~~~~~~~~
array([100,  30,  90,  94])

Upvotes: 4

Related Questions