簡體   English   中英

Pandas DataFrame。 聚合列取決於另一列中的值

[英]Pandas DataFrame. Aggregate column in depends of values in another column

有一個“訂單” dataframe 列driver_uuid, payment_type, order_price, bonus_payment payment_type 列具有“現金”、“卡”等值。 order_price 是 integer。 獎金也是 integer。 在此處輸入圖像描述

我需要按 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 相同,但用於“卡”支付類型。 我正在使用帶有 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')
    )
)

是否有可能以這種方式或其他方式做到這一點?

首先將不匹配的行替換為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')
    )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM