Testing dictionary entries in pandas lambda functions

When I do this:

โ€‹df['ViewClass'] = df['dataset_id'].apply(
    lambda x: classdict[str(x)] if classdict[str(x)] else '???' )

      

It explodes if the key doesn't exist. How can I get the lambda function to behave and put in '???'

if the key doesn't exist?

I come from a Perl background and this explains my failed attempt here.

+3


source to share


3 answers


You seem to be looking for Series.map:

df['ViewClass'] = df['dataset_id'].astype(str).map(classdict).fillna('???')

      



.astype(str)

converts the column to an object. Then it .map

looks up the corresponding values โ€‹โ€‹in the dictionary. It returns nan

if it cannot find the key. Therefore, at the end, you fill in with the nan

specified value.

It is generally best to use vectorized methods such as map

iterating over a Series or DataFrame instead (that's what applies).

+3


source


Use method dict.get()

like:



classdict.get(str(x), '???')

      

+6


source


In terms of python basics, to check if is str(x)

in classdict

, use

str(x) in classdict

      

i.e. lambda would be

lambda x: classdict[str(x)] if str(x) in classdict else '???'

      

For this application, other solutions are better.

+1


source







All Articles