Sai Rajesh
Sai Rajesh

Reputation: 1992

remapping multiple column values with multiple dictionary in dataframe using python pandas

i have following dataframe format

name,state,country
a,1,67
b,2,52

i have following state code and country code mapping dictionary

state_map = { 1:'tn', 2:'kerala' }
country_map = { 67: 'usa', 52: 'india'
i have used data.replace({'state':state_map,'country':'country_map'}) its working if we give one column mapping but not working for multiple mapping dictionary

Upvotes: 0

Views: 1606

Answers (2)

Kiran Ramamurthy
Kiran Ramamurthy

Reputation: 31

The above solution takes lot of time, hence use below code instead for better performance(Note fillna used to fillup default values when match not found):-

df['state'].map(state_map).fillna(0)
df['country'].map(country_map).fillna(0)

Upvotes: 0

cdwoelk
cdwoelk

Reputation: 101

From the documentation if giving a dict to replace:

  • Nested dictionaries, e.g., {‘a’: {‘b’: nan}}, are read as follows: look in column ‘a’ for the value ‘b’ and replace it with nan. You can nest regular expressions as well. Note that column names (the top-level dictionary keys in a nested dictionary) cannot be regular expressions.

So for your case your dict looks like:

r_map = {'state':{'1':'tn', '2':'kerala'},'country':{'67':'usa', '52':'india'}}

Use it like this:

df.replace(r_map)

Upvotes: 2

Related Questions