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 load JSON to Dataframe with key value pair as two colums

I have some JSON, that I would like to load into a dataframe, but would like to retain the key/value pair structure.

I’ve tried this:

    body = '''{
        "groupId": "1",
        "categories":[
            {
                "model":"xxx",
                "colour":"Black",
                "width":"100",
                "height":"200"
            }
        ]
    }'''
    
    categories = json.loads(body)['categories']
    
    dfQuery = pd.DataFrame(categories)
    
    print(dfQuery)

and that gives me 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

enter image description here

But I need it pivoted and to alias the columns so that it appears like this:

enter image description here

I’ve tried transposing, but can’t work out how to alias the 2 columns:

dfQuery = pd.DataFrame.from_dict(categories).T

>Solution :

Transposing is right, but you also need to reset the index and rename the columns:

dfQuery = dfQuery.T.reset_index().rename({'index': 'type', 0: 'value'}, axis=1)

Output:

>>> dfQuery
     type  value
0   model    xxx
1  colour  Black
2   width    100
3  height    200
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