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

Handle json using Pandas json_normalize

My goal is to convert a dictionary to a Pandas dataframe using only json_normalize.

What I have:

d = {'date': '20-NOV-2021', 'sector': {'South': 8, 'Est': 9, 'North': 12, 'Ouest': 9}}
pd.json_normalize(d)

       date  sector.South  sector.Est  sector.North  sector.Ouest
20-NOV-2021             8           9            12             9

What I’m looking for:

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

sector   value          date
South    8       20-NOV-2021
Est      9       20-NOV-2021
North    12      20-NOV-2021
Ouest    9       20-NOV-2021

>Solution :

I think you need to convert your sector data into a slightly different format:

d['sector'] = [{'sector': k, 'value': v} for k, v in dd['sector'].items()]
df = pd.json_normalize(d, "sector", "date")

Output:

>>> df
  sector  value         date
0  South      8  20-NOV-2021
1    Est      9  20-NOV-2021
2  North     12  20-NOV-2021
3  Ouest      9  20-NOV-2021
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