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

I am getting below error:

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

Please help

3
  • 2
    Where's else part? 3 if (x == 'high') else ... Commented May 16, 2017 at 5:06
  • 1
    Possible duplicate of Does Python have a ternary conditional operator? Commented May 16, 2017 at 5:11
  • Side note: apply() is deprecated since 2.3. It has been supplemented with direct call syntax: (lambda x:<whatever>)(value). Commented May 16, 2017 at 5:26

2 Answers 2

4

If you're going to have a if inside a lambda statement, an else must also be defined. Every lambda statement must return something, even if it's None. Change your lambda statement to this, by returning None if x isn't "high":

lambda x : 3 if x == 'high' else None # paralysis isn't necessary 
Sign up to request clarification or add additional context in comments.

Comments

1

Lambda statements need to return something, and without an else clause the return may be ambiguous. Change to:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.