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.
source to share
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).
source to share