lambda中的语法错误,带有if表达式

时间:2017-05-16 05:03:29

标签: python python-3.x

basic_salary['dem_education_level_numeric']=basic_salary['dem_education_level'].apply(lambda x : 3 if (x == 'high'))

我收到以下错误:

SyntaxError: invalid syntax (<ipython-input-20-80adac538241>, line 1)
  File "<ipython-input-20-80adac538241>", line 1
    basic_salary['dem_education_level_numeric']=basic_salary['dem_education_level'].apply(lambda x : 3 if (x == 'high'))
                                                                                                                       ^
SyntaxError: invalid syntax

请帮忙

2 个答案:

答案 0 :(得分:1)

如果您要在if语句中添加lambda,则还必须定义else。每个lambda语句都必须返回一些内容,即使它是None。如果lambda不是None,则返回x,将您的"high"语句更改为此

lambda x : 3 if x == 'high' else None # paralysis isn't necessary 

答案 1 :(得分:1)

Lambda语句需要返回一些内容,如果没有else子句,则返回可能不明确。改为:

basic_salary['dem_education_level_numeric']=basic_salary['dem_education_level'].apply(lambda x : 3 if x == 'high' else 0)