Vijaya Bhaskar
Vijaya Bhaskar

Reputation: 49

how to convert multi index data to dataframe

i have a list like this.

result =  [
{'Global': {'NewConfirmed': 100282, 'TotalConfirmed': 1162857, 'NewDeaths': 5658, 'TotalDeaths': 63263, 'NewRecovered': 15405, 'TotalRecovered': 230845}},
{'Global': {'NewConfirmed': 106598, 'TotalConfirmed': 1252421, 'NewDeaths': 5972, 'TotalDeaths': 67572, 'NewRecovered': 11066, 'TotalRecovered': 241599}}
]

I want to convert this data into dataframe as below.

   NewConfirmed  TotalConfirmed  NewDeaths  TotalDeaths  NewRecovered  TotalRecovered
0        100282         1162857       5658        63263         15405          230845
1        106598         1252421       5972        67572         11066          241599

tried many possibilites, but could not find a solution.

Upvotes: 1

Views: 46

Answers (1)

jezrael
jezrael

Reputation: 862581

Use list comprehension for select by Global with DataFrame constructor:

df = pd.DataFrame([x['Global'] for x in result])
print (df)
   NewConfirmed  TotalConfirmed  NewDeaths  TotalDeaths  NewRecovered  \
0        100282         1162857       5658        63263         15405   
1        106598         1252421       5972        67572         11066   

   TotalRecovered  
0          230845  
1          241599  

If more keys in outer dictionaries use json.json_normalize:

from pandas.io.json import json_normalize

df = json_normalize(result)
print (df)
   Global.NewConfirmed  Global.TotalConfirmed  Global.NewDeaths  \
0               100282                1162857              5658   
1               106598                1252421              5972   

   Global.TotalDeaths  Global.NewRecovered  Global.TotalRecovered  
0               63263                15405                 230845  
1               67572                11066                 241599  

Upvotes: 4

Related Questions