Home > database >  Mapping of values from nested dictionary to data frame does not work properly
Mapping of values from nested dictionary to data frame does not work properly

Time:11-11

I have a nested dict (contains column and value) and I am trying to replace/map the values to a data frame. It looks like this:

dict = 
{ 
'customer_id': { '1': '47598374539', '2': '859082093'}, 
'age': { '1': '55 ', '2': '25'}, 
'gender': { '1': 'male', '2': 'female'}
}

Now, I want to replace the values with the corresponding column in this data frame:

df=
customer_id | age | gender | other columns..
1           | 1   | 1      | something
2           | 2   | 1      | something

So that it looks like this:

df=
customer_id | age | gender | other columns..
47598374539 | 55  | male   | something
859082093   | 25  | male   | something

I tried the df.replace(dict) but somehow not all values were changed (only a subset) and I wonder if it has to do that the same key exists multiple times in my nested dict (but for a distinct column)?

What seems to be the best path?

CodePudding user response:

You can create a pd.DataFrame from a dictionary using pandas.DataFrame.from_dict, in your case :

import pandas as pd
your_dict = { 
'customer_id': { '1': '47598374539', '2': '859082093'}, 
'age': { '1': '55 ', '2': '25'}, 
'gender': { '1': 'male', '2': 'female'}
}
df = pd.DataFrame.from_dict(your_dict)
print(df)

will output :

Out[6]: 
   customer_id  age  gender
1  47598374539  55     male
2    859082093   25  female
  • Related