pandas groupby agg从一列获取最大值,并从另一列获取值

2024-09-27 07:25:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个购买数据框架:

product_id    count    timestamp           customer_id
1             1        2021-10-04 10:20    a
1             3        2021-10-04 10:21    b
2             4        2021-10-04 10:00    c
1             2        2021-10-03 10:00    c

我使用下面的groupby和agg创建一个报告,其中包括计数的总和和平均值,以及最新的购买时间戳

report = (
    df.groupby(product_id).agg(
        sum=pd.NamedAgg(column="count", aggfunc="sum"),
        mean_count=pd.NamedAgg(column="count", aggfunc="mean"),
        latest_purchase_time=pd.NamedAgg(column="timestamp", aggfunc="max")
    )
)

我想在此报告中包含与最新购买时间戳对应的客户id。有办法做到这一点吗

例如:

product_id    sum    mean_count    latest_purchase_timestamp   *customer_id*
1             6      2             2021-10-04 10:21            b
2             4      4             2021-10-04 10:00            c

Tags: id报告count时间columncustomerproductmean
1条回答
网友
1楼 · 发布于 2024-09-27 07:25:13

首先将customer_id转换为index,以便通过^{}最大timestamp获得值:

report = (
    df.set_index('customer_id')
      .groupby('product_id').agg(
        sum=pd.NamedAgg(column="count", aggfunc="sum"),
        mean_count=pd.NamedAgg(column="count", aggfunc="mean"),
        latest_purchase_time=pd.NamedAgg(column="timestamp", aggfunc="max"),
        customer_id=pd.NamedAgg(column="timestamp", aggfunc="idxmax")
    )
)
print (report)
            sum  mean_count latest_purchase_time customer_id
product_id                                                  
1             6           2  2021-10-04 10:21:00           b
2             4           4  2021-10-04 10:00:00           c

相关问题 更多 >

    热门问题