简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM