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!
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
elsein the ternaryifstatementsp1_new_dict[x] if x in sp1_new_dict.keys()is not a valid expression, thus it cannot go there, hence the SyntaxErrorelseexpression must be provided