![](/img/trans.png)
[英]Pandas Dataframe groupby one column and sum of all other columns
[英]Pandas Dataframe groupby two columns and sum up a column
我有以下格式的pandas數據框:
d = {'buyer_code': ['A', 'B', 'C', 'A', 'A', 'B', 'B', 'A', 'C'], 'dollar_amount': ['2240.000', '160.000', '300.000', '10920.000', '10920.000', '235.749', '275.000', '10920.000', '300.000']}
df = pd.DataFrame(data=d)
df
這是我的數據框的樣子:
buyer_code dollar_amount
0 A 2240.000
1 B 160.000
2 C 300.000
3 A 10920.000
4 A 10920.000
5 B 235.749
6 B 275.000
7 A 10920.000
8 C 300.000
我使用groupby列出了每個買家,並列出了相應的美元金額。
df.groupby(['buyer_code', 'dollar_amount']).size()
結果如下:
buyer_code dollar_amount
A 10920.000 3
2240.000 1
B 160.000 1
235.749 1
275.000 1
C 300.000 2
dtype: int64
現在,我希望將dollarAmount乘以其計數,然后再乘以每個購買者的所有金額之和。
Lets say for example buyer_code "A" should have (10920.000 * 3) + (2240.000 * 1)
結果應該是這樣的:
buyer_code dollar_amount
A 35000
B 670.749
C 600.000
如何獲得此輸出?
使用groupby
+總sum
:
df['dollar_amount'] = df['dollar_amount'].astype(float)
a = df.groupby('buyer_code', as_index=False).sum()
print (a)
buyer_code dollar_amount
0 A 35000.000
1 B 670.749
2 C 600.000
unstack
結果unstack
,然后在結果及其dot
之間用dot
進行矩陣乘法-
i = df.groupby(['buyer_code', 'dollar_amount']).size().unstack()
i.fillna(0).dot(i.columns.astype(float))
buyer_code
A 35000.000
B 670.749
C 600.000
dtype: float64
要么,
i.fillna(0).dot(i.columns.astype(float))\
.reset_index(name='dollar_amount')
buyer_code dollar_amount
0 A 35000.000
1 B 670.749
2 C 600.000
如果您要對中間groupby
結果執行其他操作,則需要進行計算,這沒關系。 如果不是,則groupby
+ sum
在這里更有意義。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.