Shiva Rama Krishna
Shiva Rama Krishna

Reputation: 395

pandas read_json gives multiple columns instead of rows

i am trying to convert json to pandas dataframe using read_json, but it is always creating extra columns instead of rows

json:

'[{"1981121": {"Summary": "Tasa"}}, {"1981123": {"Summary": "This fox only jumps on the top"}}]'

code:

pd.read_json(json,orient='index')

result:

                 0                                              1
1981121  {'Summary': 'Tasa'}                                   NaN
1981123         NaN                {'Summary': 'This fox only jumps on the top'}

i have tried different values for 'orient' arg yet it is the same

how can i get dataframe in this manner

               0         
1981121  {'Summary': 'Tasa'}                                           
1981123  {'Summary': 'This fox only jumps on the top'}

Upvotes: 0

Views: 1510

Answers (1)

John Zwinck
John Zwinck

Reputation: 249552

Pandas expects each record to be a tuple, not a dict. Here's one way to make it work:

items = [next(iter(d.items())) for d in json]
pd.DataFrame.from_items(items, orient='index', columns=['Summary'])

Then you get:

                                Summary
1981121                            Tasa
1981123  This fox only jumps on the top

Upvotes: 1

Related Questions