Kaw*_*rZZ 4 python sorting sum pandas pandas-groupby
鉴于以下数据帧
user_ID product_id amount
1 456 1
1 87 1
1 788 3
1 456 5
1 87 2
... ... ...
Run Code Online (Sandbox Code Playgroud)
第一列是客户的ID,第二列是他购买的产品的ID,'amount'表示当天购买的产品数量(日期也考虑在内)。客户每天可以购买任意数量的产品。我想计算客户购买每种产品的总次数,所以我应用了一个groupby
df.groupby(['user_id','product_id'], sort=True).sum()
Run Code Online (Sandbox Code Playgroud)
现在我想对每组中的金额总和进行排序。有什么帮助吗?
stu*_*ent 10
假设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
Run Code Online (Sandbox Code Playgroud)
然后你可以使用,groupby和sum以前一样,此外,你可以按两列对值进行排序,[user_ID, amount]并ascending=[True,False]引用用户的升序和每个用户的金额降序:
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)
Run Code Online (Sandbox Code Playgroud)
输出:
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
Run Code Online (Sandbox Code Playgroud)
小智 6
这将为您提供前 5 个最大的:
# n = number of rows you want to return
df.groupby(['user_id'])['amount'].sum().nlargest(n)
Run Code Online (Sandbox Code Playgroud)