【发布时间】:2013-07-17 16:58:48
【问题描述】:
另一个新手熊猫问题。我想将 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 个级别的 MultiIndices(而不是 2 个级别)?
回答
感谢DSM's answer,我发现我其实只需要使用元组连接r+(c,),我上面的二维循环就变成了N维:
after = {r + (c,): df.ix[r,c] for c in df.columns for r in df.index}
【问题讨论】: