Wolfy
Wolfy

Reputation: 458

Apply map on pandas column only if the key exisits

I am trying to this in python

df_svn_subset['job_title_name'] = df_svn_subset['job_title_name'].map(alias_job_titles)

I noticed that when I am checking the existence of null values in the job_title_name column that it goes up after applying the latter above. Therefore, how can I apply the latter above only if the key exists otherwise just ignore?

Upvotes: 0

Views: 1283

Answers (2)

Matthias Fripp
Matthias Fripp

Reputation: 18625

You could use a wrapper function instead of the dictionary itself, like this:

df_svn_subset['job_title_name'] = df_svn_subset['job_title_name'].map(lambda x: alias_job_titles.get(x, x))

This will try to lookup the value of each cell (x) in the dictionary, and if it's missing, it will use the current value of x instead.

Upvotes: 1

Naveed
Naveed

Reputation: 11650

update with the job_title_name, when map returns null using fillna

df_svn_subset['job_title_name'] = (df_svn_subset['job_title_name'].map(alias_job_titles)
                                   .fillna(df_svn_subset['job_title_name']))

Upvotes: 1

Related Questions