[英]Get the sum of a multikey dict by one key and add it to a datfarme column in Python?
[英]How to group by a multikey dict in Python by one key?
我這里有一個多鍵字典。 我正在嘗試按第一個鍵(A,B)按字典分組並將其轉換為轉置的 dataframe 並將其寫入 csv 文件。
>>> dic= { ('A',1): 4, ('A',1):2, ('B', 1): 2, ('A', 2): 5, ('B', 2):3}
>>> dic
{('A', 1): 2, ('B', 1): 2, ('A', 2): 5, ('B', 2): 3}
>>> df = pd.DataFrame(dic.items()).groupby(0).sum()
>>> df
1
0
(A, 1) 2
(A, 2) 5
(B, 1) 2
(B, 2) 3
這是我到目前為止一直在做的事情:
>>> df = pd.DataFrame(dic.items()).groupby(0).sum()
>>> df
1
0
(A, 1) 4
(A, 2) 5
(B, 1) 2
(B, 2) 3
>>> df_t = df.T
0 (A, 1) (A, 2) (B, 1) (B, 2)
1 4 5 2 3
>>> df_t.to_csv(./file.csv)
我想要得到的是這樣的:
1 2
A 6 5
B 2 3
首先,字典從不包含重復的鍵(即字典可以保存 1 個鍵對應 N 個值,但不能保存 N 個鍵對應 1 個值)。 在當前情況下,您的dic
包含重復的鍵,因此在執行時它將僅采用最新值。 如果您的dic
包含重復鍵,可能的解決方案是將值放在列表中。 就像是
dic = { ('A',1): 4, ('A',1):2, ('B', 1): 2, ('A', 2): 5, ('B', 2):3}
應該,
dic = {('A',1):[4,2], ('B', 1): [2], ('A', 2): [5], ('B', 2):[3]}
現在解決方案部分,
import pandas as pd
#data
dic = {('A',1):[4,2], ('B', 1): [2], ('A', 2): [5], ('B', 2):[3]}
#Converting dic to dataframe object
df = pd.DataFrame(dic.items())
#Explode will convert list of values to row like structure
exp = df[1].explode().to_frame().reset_index()
#Merging df and exp to combine results
df = df.reset_index().merge(exp, on = 'index', how = 'left')
#Converting tuple of keys into separate columns
df[['i1','i2']] = df[0].apply(pd.Series)
#Summing up the result and then pivoting them to get desired result
df.groupby(['i1','i2'])['1_y'].sum().reset_index().pivot(index=['i1'],columns=['i2'],values=['1_y'])
#Renaming columns and index
res.columns = ['1','2']
res.index.names = ['']
res
Output:
1 2
A 6 5
B 2 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.