Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambda including if...elif...else

I want to apply a lambda function to a DataFrame column using if...elif...else within the lambda function.

The df and the code are something like:

df=pd.DataFrame({"one":[1,2,3,4,5],"two":[6,7,8,9,10]})  df["one"].apply(lambda x: x*10 if x<2 elif x<4 x**2 else x+10) 

Obviously, this doesn't work. Is there a way to apply if....elif....else to a lambda? How can I get the same result with List Comprehension?

like image 926
2Obe Avatar asked Jul 08 '17 22:07

2Obe


1 Answers

Nest if .. elses:

lambda x: x*10 if x<2 else (x**2 if x<4 else x+10) 
like image 94
Uriel Avatar answered Sep 28 '22 10:09

Uriel