如何将多标头熊猫数据框转换为嵌套词典列表

San*_*ta7 1 python pandas

我有一个带有多个标头的熊猫数据框。我想知道如何将其转换为嵌套目录列表。熊猫数据框中的每一行将是列表中的嵌套字典。

这是一个例子

#Creaet an example multiheader dataframe

col =['id','x, single room','x, double room','y, single room','y, double room' ]
df = pd.DataFrame([[1,2,3,4,5], [3,4,7,5,3]], columns=col)
a = df.columns.str.split(', ', expand=True).values
#swap values in NaN and replace NAN to ''
df.columns = pd.MultiIndex.from_tuples([('', x[0]) if pd.isnull(x[1]) else x for x in a])
df
Run Code Online (Sandbox Code Playgroud)

结果

        x   y
id  single room double room single room double room
0   1   2   3   4   5
1   3   4   7   5   3
Run Code Online (Sandbox Code Playgroud)

这是我想转换为嵌套字典列表的数据框。所以这是理想的结果

[{'id': 1,
  'x': {'double room': 3, 'single room': 2},
  'y': {'double room': 5, 'single room': 4}},
 {'id': 3,
  'x': {'double room': 7, 'single room': 4},
  'y': {'double room': 3, 'single room': 5}}]
Run Code Online (Sandbox Code Playgroud)

在下面的代码中,我直接创建此列表。

firstDict = { 'id':1, 'x':{'single room':2, 'double room':3}, 'y':{'single room':4, 'double room':5} }
secondDict = { 'id':3, 'x':{'single room':4, 'double room':7}, 'y':{'single room':5, 'double room':3} }
dictList = []
dictList.append( firstDict )
dictList.append( secondDict )
dictList

[{'id': 1,
  'x': {'double room': 3, 'single room': 2},
  'y': {'double room': 5, 'single room': 4}},
 {'id': 3,
  'x': {'double room': 7, 'single room': 4},
  'y': {'double room': 3, 'single room': 5}}]
Run Code Online (Sandbox Code Playgroud)

因此,在总结,如何转换我的数据帧df到什么dictList是。

编辑:

这是一个最小的示例,我正在寻找的解决方案应该推广到更长数量的标头。

Dan*_*ejo 6

我认为没有做到这一点的直接方法,也就是说,可以在之后使用stack + to_dict和一些后期处理:

# prepare the DataFrame
df = df.set_index(('', 'id')).stack(level=0)
df.index.names = ['id', None]

# convert to a dicts of dicts
d = {}
for (idi, key), values in df.to_dict('index').items():
    d.setdefault(idi, {}).update({key: values})

# convert d to list of dicts
result = [{'id': k, **values} for k, values in d.items()]
Run Code Online (Sandbox Code Playgroud)

输出量

[{'id': 1,
  'x': {'double room': 3, 'single room': 2},
  'y': {'double room': 5, 'single room': 4}},
 {'id': 3,
  'x': {'double room': 7, 'single room': 4},
  'y': {'double room': 3, 'single room': 5}}]
Run Code Online (Sandbox Code Playgroud)