有一个包含 driver_uuid, payment_type, order_price, bonus_payment
列的“订单”数据框。
payment_type 列具有诸如“现金”、“卡”之类的值。 order_price 是一个整数。奖金也是一个整数。
Firebase database image
我需要按 driver_uuid 对订单进行分组,然后为每种付款类型计算 order_price 总和并将这些总和添加到单独的列中。所以我需要生成的 df 与这样的列:
[driver_uuid, cash_order_price_sum, card_order_price_sum, bonus_payment_sum]
cash_order_price_sum 列包含 Payment_type 为“cash”的 orders_ 的 order_price 总和。 card_order_price_sum 是相同的,但对于“卡”payment_type。 我正在使用带有 NamedAgg 的 groupby 和 agg 函数。
grouped_orders = (
orders.groupby('driver_uuid')
.agg(
cash_order_price_sum= here sum(real_price) if payment_type == 'cash',
card_order_price_sum= here sum(real_price) if payment_type == 'card',
bonus_payment_sum=pandas.NamedAgg('bonus_payment', 'sum')
)
)
是否可以通过这种方式或其他方式来实现?
答案 0 :(得分:2)
首先将不匹配的行替换为 Series.where
中的缺失值,然后将辅助列传递给 agg
:
grouped_orders = (
orders
.assign(cash = orders['order_price'].where(orders['payment_type'] == 'cash'),
card = orders['order_price'].where(orders['payment_type'] == 'card'))
.groupby('driver_uuid')
.agg(
cash_order_price_sum=('cash', 'sum'),
card_order_price_sum=('card', 'sum'),
bonus_payment_sum=('bonus_payment', 'sum')
)
)