Davood Norouzi
Davood Norouzi

Reputation: 53

Pandas lambda function syntax error (with dictionary)

I use lambda functions in Python a lot. All of a sudden, I cannot figure out why is there a syntax error message for this:

table['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_dict[x] if x in sp1_new_dict.keys())

Any ideas? Thanks!

Upvotes: 0

Views: 86

Answers (1)

C.Nivs
C.Nivs

Reputation: 13106

You need an else. Boiling down your error:

x = 1 if True

  File "<stdin>", line 1
    x = 1 if True
                 ^
SyntaxError: invalid syntax


# No error here
x = 1 if True else 2

Since you are using a dictionary, maybe use dict.get:

table['sp1 name'] = table['sp1'].apply(lambda x: sp1_new_dict.get(x))

Which returns None if the key isn't present

Upvotes: 2

Related Questions