簡體   English   中英

Pandas:使用MultiIndex將DataFrame轉換為dict

[英]Pandas: Convert DataFrame with MultiIndex to 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的回答 ,我發現我實際上只需要使用元組連接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}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM