3

I have a pandas dataframe which looks like as follows:

df = 
    key     value
1   Level       1
2   Age        35 
3   Height    180
4   Gender      0
...

and a dictionary as follows:

my_dict = {
           'Level':{0: 'Low', 1:'Medium', 2:'High'},
           'Gender': {0: 'Female', 1: 'Male'}
          }

I want to map from the dictionary to the dataframe and change the 'value' column with its corresponding value in the dictionary such as the output becomes:

    key        value
1   Level     Medium
2   Age           35 
3   Height       180
4   Gender    Female
...

Its okay for other values in the column become a string as well. How can I achieve this? Thanks for the help.

3
  • 1
    The dictionary looks wrong. Is that supposed to be a dict within a dict? Commented Nov 1, 2020 at 18:03
  • Corrected it, sorry. Commented Nov 1, 2020 at 18:06
  • Please note that dictionary might have many more keys, so manual mapping would not be very feasible. Commented Nov 1, 2020 at 18:14

2 Answers 2

6

Check with replace

out = df.set_index('key').T.replace(my_dict).T.reset_index()
out
Out[27]: 
      key   value
0   Level  Medium
1     Age      35
2  Height     180
3  Gender  Female
Sign up to request clarification or add additional context in comments.

Comments

0

df.at[1, 'value'] = my_dict['Level'][df.at[1, 'value']]
df.at[4, 'value'] = my_dict['Gender'][df.at[4, 'value']]

Comments

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.