s_khan92
s_khan92

Reputation: 979

How to map value from nested dictionary to multiple columns in dataframe

For example: I have df like this:

id      Status         Country       Income
1          4               2          3
2          5               3          2 

and dictionary like this:

d_dict = {Status : { '4':'Married', '5':'UnMarried'},
        Country: { '2': 'Japan' , '3': 'China'},
        Income: {'3': "5000-10000", 2: "11000-20000"}}

I want to map the values based on nested dictionary. I can do for one column like this:

for k,v in d_dict.items():
    max_d[k] = max(v, key=v.get)
df['Status'] = df['Status'].map(max_d)

But I have more than 2000 columns and I am not sure how I can do for multiple columns.

Upvotes: 0

Views: 50

Answers (1)

BENY
BENY

Reputation: 323226

You can try replace

df=df.astype(str).replace(d_dict)
df
Out[259]: 
   id     Status Country      Income
0   1    Married   Japan  5000-10000
1   2  UnMarried   China 11000-20000

Upvotes: 1

Related Questions