python – Pandas:使用MultiIndex将DataFrame转换为dict

另一个新手熊猫问题.我想将DataFrame转换为字典,但其方式与DataFrame.to_dict()函数提供的方式不同.按示例说明:

df = pd.DataFrame({'co':['DE','DE','FR','FR'],
                   'tp':['Lake','Forest','Lake','Forest'],
                   'area':[10,20,30,40],
                   'count':[7,5,2,3]})
df = df.set_index(['co','tp'])

之前:

           area  count
co tp
DE Lake      10      7
   Forest    20      5
FR Lake      30      2
   Forest    40      3

后:

{('DE', 'Lake', 'area'): 10,
 ('DE', 'Lake', 'count'): 7,
 ('DE', 'Forest', 'area'): 20,
 ...
 ('FR', 'Forest', 'count'): 3 }

dict键应该是由索引行列标题组成的元组,而dict值应该是单独的DataFrame值.对于上面的例子,我设法找到了这个表达式:

after = {(r[0],r[1],c):df.ix[r,c] for c in df.columns for r in df.index}

如何推广此代码以适用于具有N级(而不是2级)的MultiIndices?

回答

感谢DSM’s answer,我发现我实际上只需要使用元组连接r(c,),我上面的二维循环变为N维:

after = {r + (c,): df.ix[r,c] for c in df.columns for r in df.index}

最佳答案 怎么样:

>>> df
           area  count
co tp                 
DE Lake      10      7
   Forest    20      5
FR Lake      30      2
   Forest    40      3
>>> after = {r + (k,): v for r, kv in df.iterrows() for k,v in kv.to_dict().items()}
>>> import pprint
>>> pprint.pprint(after)
{('DE', 'Forest', 'area'): 20,
 ('DE', 'Forest', 'count'): 5,
 ('DE', 'Lake', 'area'): 10,
 ('DE', 'Lake', 'count'): 7,
 ('FR', 'Forest', 'area'): 40,
 ('FR', 'Forest', 'count'): 3,
 ('FR', 'Lake', 'area'): 30,
 ('FR', 'Lake', 'count'): 2}
点赞