You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas按product_id分组agg取最大timestamp时如何获取对应customer_id

实现方案

你可以通过以下两种常用方式实现需求,可根据数据量大小选择:

前置准备

首先确保timestamp列是 pandas 可识别的时间类型,避免比较出错:

import pandas as pd
df['timestamp'] = pd.to_datetime(df['timestamp'])

方法1:直接在原有agg逻辑上扩展(适合小数据量)

直接在原有聚合规则里新增自定义聚合函数,匹配每个分组最大时间对应的customer_id:

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"),
        # 新增字段:取当前分组内时间等于最大时间的customer_id
        customer_id=pd.NamedAgg(column="customer_id", aggfunc=lambda x: x[df.loc[x.index, 'timestamp'] == x.max()].iloc[0])
    )
)

如果同一商品同一最新时间存在多笔订单,把.iloc[0]替换为.tolist()即可返回所有对应用户ID列表。

方法2:先排序再聚合(适合大数据量,性能更高)

先对全表按时间升序排序,分组后最后一条记录就是最新购买记录,直接取对应字段值即可,避免每个分组重复计算时间匹配逻辑:

# 按时间戳升序排序,保证同分组内最后一行是最新记录
df_sorted = df.sort_values('timestamp', ascending=True)
report = (
    df_sorted.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="last"),
        customer_id=pd.NamedAgg(column="customer_id", aggfunc="last")
    )
)

内容的提问来源于stack exchange,提问作者Carasel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 01:39:03