Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to normalize a dictionary of key and values pandas

My dictionary looks something like this: (has more data in the actual dictionary I’m working on)

dictionary = {'101020': {'name': 'HJ', 'grades': [90, 80, 70]}, '101520': {'name': ABC', 'grades': [100, 40, 70]}}

I want my dataframe to look like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

code          name          grades
101020        HJ              90
101020        HJ              80
101020        HJ              70
101520        ABC             100
101520        ABC             40
101520        ABC             70

Currently I’m only able to get the name and data but not the code aka the key of the dictionary with this code:

vals = [val for val in dictionary.values())
df = pd.json_normalize(vals, 'grades', ['name']) I get the data without the key
print(df)

any help would be highly appreciated 🙂

>Solution :

Try explode after using pd.DataFrame.from_dict(),

df = pd.DataFrame.from_dict(dictionary, orient='index') \
   .explode('grades') \
   .rename_axis('code') \
   .reset_index()

df

Output:

output

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading