Lambda including if…elif…else

后端 未结 3 2020
清歌不尽
清歌不尽 2020-11-28 20:29

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 smth. like:

df=pd.         


        
3条回答
  •  庸人自扰
    2020-11-28 21:31

    For readability I prefer to write a function, especially if you are dealing with many conditions. For the original question:

    def parse_values(x):
        if x < 2:
           return x * 10
        elif x < 4:
           return x ** 2
        else:
           return x + 10
    
    df['one'].apply(parse_values)
    

提交回复
热议问题