python dataframe index 两维_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}

Original: https://blog.csdn.net/weixin_39886547/article/details/114910593
Author: weixin_39886547
Title: python dataframe index 两维_python – Pandas:使用MultiIndex将DataFrame转换为dict

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/679219/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球