如何解决基于大熊猫中的groupby从多个列进行计算
假设我们要基于组在列之间进行计算。
原始数据框:
data = {'order_id': [1,1,2,3],'quantity': [1,3,2],'item_price': [10,6,4,5,6],}
df = pd.DataFrame(data,columns=['order_id','quantity','item_price'])
order_id | quantity | item_price
1 1 10
1 3 6
1 1 4
2 1 5
2 2 3
3 2 6
我要计算每个订单的总价,应该像这样:
order_id | quantity | item_price | order_price
1 1 10 32
1 3 6 32
1 1 4 32
2 1 5 11
2 2 3 11
3 2 6 12
我通过添加新列item_price_total
来实现这一点:
df['item_price_total'] = df['quantity'] * df['item_price']
并使用grouby(['order_id'])['item_price_total'].transform('sum')
:
order_id | quantity | item_price | item_price_total | order_price
1 1 10 10 32
1 3 6 18 32
1 1 4 4 32
2 1 5 5 11
2 2 3 6 11
3 2 6 12 12
我的问题是如何直接从分组在quantity
上的item_price
和order_id
中获得结果,而不使用item_price_total
?我的想法是将groupby(['order_id']).apply()
与lambda
函数一起使用,但是经过多次尝试,我仍然没有找到解决方案。
解决方法
感谢Anky的想法,
您可以尝试以下方法:
result = pd.DataFrame(df['quantity'].mul(df['item_price'])
.groupby(df['order_id'])
.transform('sum'),columns=['order_price'])
.join(df)
print(result)
# order_price order_id quantity item_price
# 0 32 1 1 10
# 1 32 1 3 6
# 2 32 1 1 4
# 3 11 2 1 5
# 4 11 2 2 3
# 5 12 3 2 6
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。