简体   繁体   中英

converting a nested dictionary to Pandas DataFrame

I'm trying to convert a nested dictionary to a df object.

the dictionary looks like this:

{'result': {'2011-12-01': {'A': 53, 'B': 28, 'C': 32, 'D': 0}, 
'2012-01-01': {'A': 51, 'B': 35, 'C': 49, 'D': 0},
 '2012-02-01': {'A': 63, 'B': 32, 'C': 56, 'D': 0}}}

and my goal is to have a table with the dates(second level keys) using as an index, and the A,B,C,D as columns.

date A B C D
2011-12-01 53 28 32 0
2012-01-01 51 35 49 0

I tried to use a for loop to grab the inner keys/values and append() it to a DF, but all I've got was a long DF with a date index followed by a plain index.

My failed attempts:

print(sorted(columns[0].values()))
df = pd.DataFrame(index=result['result'].keys() , columns= columns[0].keys())
for i in range(len(columns)):
    a=sorted(columns[i].items())
    df=df.append(a)
print(df.to_string())

You can simply use:

df = pd.DataFrame(d['result']).T

Or:

df = pd.DataFrame.from_dict(d['result'], orient='index')

Output:

             A   B   C  D
2011-12-01  53  28  32  0
2012-01-01  51  35  49  0
2012-02-01  63  32  56  0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM