Python 将多索引数据帧转换为嵌套字典

Python 将多索引数据帧转换为嵌套字典,python,pandas,Python,Pandas,我有一个pandas多索引数据框,我正试图将其输出为嵌套字典 # create the dataset data = {'clump_thickness': {(0, 0): 274.0, (0, 1): 19.0, (1, 0): 67.0, (1, 1): 12.0, (2, 0): 83.0, (2, 1): 45.0, (3, 0): 16.0, (3, 1): 40.0, (4, 0): 4.0, (4, 1): 54.0, (5, 0): 0.0, (5, 1): 69.0, (6,

我有一个pandas多索引数据框,我正试图将其输出为嵌套字典

# create the dataset
data = {'clump_thickness': {(0, 0): 274.0, (0, 1): 19.0, (1, 0): 67.0, (1, 1): 12.0, (2, 0): 83.0, (2, 1): 45.0, (3, 0): 16.0, (3, 1): 40.0, (4, 0): 4.0, (4, 1): 54.0, (5, 0): 0.0, (5, 1): 69.0, (6, 0): 0.0, (6, 1): 0.0, (7, 0): 0.0, (7, 1): 0.0, (8, 0): 0.0, (8, 1): 0.0, (9, 0): 0.0, (9, 1): 0.0}}
df = pd.DataFrame(data)
df.head()
#      clump_thickness
# 0 0            274.0
#   1             19.0
# 1 0             67.0
#   1             12.0
# 2 0             83.0
df
是我想要作为嵌套字典输出的数据帧。我正在寻找的输出形式如下-

{"0":
{
  "0":274,
  "1":19
},
"1":{
  "0":67,
  "1":12
},
"2":{
  "0":83,
  "1":45
},
"3":{
  "0":16,
  "1":40
},
"4":{
  "0":4,
  "1":54
},
"5":{
  "0":0,
  "1":69
}
}
在这里,第一个索引构成最外层字典的键。对于每个键,我们都存储了一个字典,其键是第二个索引中的值

当我执行
df.to_dict()
时,多索引将作为元组返回,而不是嵌套。我如何做到这一点?

对于我的工作:

d = {l: df.xs(l)['clump_thickness'].to_dict() for l in df.index.levels[0]}
另一种类似的解决方案,但是
系列
所必需的过滤列:

d = df.groupby(level=0).apply(lambda df: df.xs(df.name).clump_thickness.to_dict()).to_dict()

print (d)

{0: {0: 274.0, 1: 19.0},
 1: {0: 67.0, 1: 12.0},
 2: {0: 83.0, 1: 45.0},
 3: {0: 16.0, 1: 40.0},
 4: {0: 4.0, 1: 54.0},
 5: {0: 0.0, 1: 69.0},
 6: {0: 0.0, 1: 0.0},
 7: {0: 0.0, 1: 0.0},
 8: {0: 0.0, 1: 0.0},
 9: {0: 0.0, 1: 0.0}}

但不同的是,这是一个系列,有一个数据帧:(另一个解决方案让人感觉像是一个被复制者,更好的链接答案你会如何对一个系列而不是一个数据帧这样做?@Mingo如果df是系列,只需省略
['clump_thickness']
df.unstack().clump_thickness.apply(lambda x: x.to_dict(), axis=1).to_dict()