简体   繁体   中英

pandas dataframe from nested dictionary with uneven depth

I have a dictionary of the following form:

{'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}

I want to create a df like this:

在此处输入图片说明

What is the best way to achieve this?

If you have only 2 levels:

import pandas as pd

d = {'x': 1, 'y': 2, 'z':{'a': 3, 'b': 4}, 'w': {'a': 5, 'b': 6}}

data = {}
for k1, v1 in d.items():
    if isinstance(v1, dict):
        for k2, v2 in v1.items():
            data[(k1, k2)] = v2
    else:
        data[(k1, '')] = v1

df = pd.DataFrame([data.values()], columns=data)

Output:

>>> df
   x  y  z     w      # index, level 1
         a  b  a  b   # index, level 2
0  1  2  3  4  5  6   # values

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