简体   繁体   中英

How to convert a nested dictionary to pandas DataFrame

I've been struggling with this for a while. How to convert a dictionary each element of which looks like this

{'00OZ2dKSA5jUfvF': {1: (48947218088,),
      2: (48947218089,),
      3: (48947218088, 48947218089)}}

into a dataframe that will look like this?

id combination_id value
00OZ2dKSA5jUfvF 1 48947218088
00OZ2dKSA5jUfvF 2 48947218089
00OZ2dKSA5jUfvF 3 48947218088
00OZ2dKSA5jUfvF 3 48947218089

You could use df.unstack and chain df.explode :

import pandas as pd

d = {'00OZ2dKSA5jUfvF': {1: (48947218088,),
      2: (48947218089,),
      3: (48947218088, 48947218089)}}

df = pd.DataFrame(d)
df = df.unstack().explode().reset_index(drop=False)
df.columns = ['id','combination_id', 'value']
print(df)

                id  combination_id        value
0  00OZ2dKSA5jUfvF               1  48947218088
1  00OZ2dKSA5jUfvF               2  48947218089
2  00OZ2dKSA5jUfvF               3  48947218088
3  00OZ2dKSA5jUfvF               3  48947218089

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