Lambda function

Hi,

I always got problem with the following script:

survey_roles_yes_WandM[‘MonthsProgramming’] = survey_roles_yes_WandM[‘MonthsProgramming’].apply(lambda x: x+1 if x == 0)

I always get the following message, could you please let me know what was wrong?

File “”, line 2
survey_roles_yes_WandM[‘MonthsProgramming’] = survey_roles_yes_WandM[‘MonthsProgramming’].apply(lambda x: x+1 if x == 0)
^
SyntaxError: invalid syntax

Thank you!

Hi @wtche17 and welcome back to the community!

I did a bit of digging and it appears that using if in a lambda function requires us to use else as well since the function needs to know what to return in the case when if is false. Please see this reference. With that said, I believe the solution to your problem would look like this:

survey_roles_yes_WandM[‘MonthsProgramming’] = 
survey_roles_yes_WandM[‘MonthsProgramming’].apply(lambda x: x+1 if x == 0 else x)

Thank you very much Mike, you solved my problem! Really didn’t know that else should alos be inside the lambda script. Many thanks again!

1 Like