0

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.

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

5 Comments

there are some columns where i don't need dictionary or i can't use... Is there any way to handle that?
Key of dictionary is always the name of column and if it matches then it should use the dictionary.
@s_khan92 not sure what you mean , the replace is match the columns first , then replace value within the dict
@s_khan92 first key in dict will match the columns , the second key will look the columns value replace the value in dict
I dont know why but its not able to match.. and giving wrong values

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.