Nicolai Schmid
Nicolai Schmid

Reputation: 1092

Python-Pandas JSON.normalize on non-Array JSON keys

I have the following JSON from a string and read it via json.load.
I would like to normalize its contents into a pandas data frame. But instead of creating a column for each "node" in the JSON graph, I want it to create a row for each depth=1 node

import pandas as pd

pd.json_normalize({'a': {'i': 1, 'm': 'msg'}, 'b': {'i': 5, 'm': 'msg2'}} )

Output:

   a.i  a.m b.i b.m
0   1   msg 5   msg2

I want this instead:

    i   m
a   1   msg 
b   5   msg2

Do you know how to achieve that?

Thank you very much!

Upvotes: 0

Views: 62

Answers (1)

Eric Truett
Eric Truett

Reputation: 3010

Use the orient='index' parameter

data = {'a': {'i': 1, 'm': 'msg'}, 'b': {'i': 5, 'm': 'msg2'}}
pd.DataFrame.from_dict(data=data, orient='index')

Output

   i     m
a  1   msg
b  5  msg2

Upvotes: 1

Related Questions