問題描述
給定以下數據幀
user_ID product_id amount
1 456 1
1 87 1
1 788 3
1 456 5
1 87 2
... ... ...
第一列是客戶的 ID,第二列是他購買的產品的 ID,如果是當天購買的產品數量,則表示金額"(日期也考慮在內).客戶每天可以隨心所欲地購買許多產品.我想計算客戶購買每種產品的總次數,所以我應用了 groupby
The first column is the ID of the customer, the second is the ID of the product he bought and the 'amount' express if the quantity of the product purchased on that given day (the date is also taken into consideration). a customer can buy many products each day as much as he wants to.
I want to calculate the total of times each product is bought by the customer, so I applied a groupby
df.groupby(['user_id','product_id'], sort=True).sum()
現在我想對每組中的金額總和進行排序.有什么幫助嗎?
now I want to sort the sum of amount in each group. Any help?
推薦答案
假設 df
是:
user_ID product_id amount
0 1 456 1
1 1 87 1
2 1 788 3
3 1 456 5
4 1 87 2
5 2 456 1
6 2 788 3
7 2 456 5
然后您可以像以前一樣使用 groupby
和 sum
,此外您可以按兩列 [user_ID, amount]
和ascending=[True,False]
表示用戶升序,每個用戶的金額降序:
Then you can use, groupby
and sum
as before, in addition you can sort values by two columns [user_ID, amount]
and ascending=[True,False]
refers ascending order of user and for each user descending order of amount:
new_df = df.groupby(['user_ID','product_id'], sort=True).sum().reset_index()
new_df = new_df.sort_values(by = ['user_ID', 'amount'], ascending=[True,False])
print(new_df)
輸出:
user_ID product_id amount
1 1 456 6
0 1 87 3
2 1 788 3
3 2 456 6
4 2 788 3
這篇關于我在 groupby 上應用了 sum(),我想對最后一列的值進行排序的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!