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

Create a pandas dataframe from a nested json file

I have the following json file:

{
    "data": {
        "start_date": "2022-10-01",
        "end_date": "2022-10-04",
        "cur": "EUR",
        "prizes": {
            "2022-10-01": {
                "coffee": 0.1448939471560284,
                "usd": 1
            },
            "2022-10-02": {
                "coffee": 0.14487923291390148,
                "usd":1
            },
            "2022-10-03": {
                "coffee": 0.1454857922753868,
                "usd": 1
            }
        }
    }
}

I want to create a dataframe which looks like this, (so without the usd column):

              coffee  
2022-10-01  0.144894  
2022-10-02  0.144879  
2022-10-03  0.145486 

This is what I tried:

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

path = r'C:\Users\Geo\Desktop\json_files\coffee.json'

df = pd.read_json(path)
df = pd.DataFrame(df['data']['prizes']['2022-10-01']['coffee']).T
print(df)

This is what I received:

   raise ValueError("DataFrame constructor not properly called!")
ValueError: DataFrame constructor not properly called!

>Solution :

Assume your json file is loaded into dictionary as data

df = pd.DataFrame(data['data']['prizes']).drop('usd').T
print(df)

              coffee
2022-10-01  0.144894
2022-10-02  0.144879
2022-10-03  0.145486
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