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

如何基于最新日期获取字符串字段最后值并汇总销售额?

解决Pandas分组取最新Item type并汇总Sales的问题

核心是要先按日期排序,再分组处理,这样last()方法才能正确拿到最新日期的Item type,同时完成Sales的汇总。以下是具体实现步骤:

1. 转换日期列格式

原始日期是字符串(比如"Jan 1"),必须转成datetime类型才能正确判断日期先后:

import pandas as pd

# 构造示例数据
data = {
    'Item': ['Apple', 'Apple', 'Apple'],
    'Item type': ['Healthy', 'Vegan', 'Fruit'],
    'Date': ['Jan 1', 'Jan 5', 'Jan 7'],
    'Sales': [10, 5, 2]
}
df = pd.DataFrame(data)

# 转换日期格式
df['Date'] = pd.to_datetime(df['Date'], format='%b %d')

2. 排序后分组聚合

先按Item分组,每组内按Date升序排序,确保最新日期的记录排在每组最后:

# 按Item和Date排序
df_sorted = df.sort_values(by=['Item', 'Date'])

# 分组处理:取每组最后一行的Item type,同时求和Sales
result = df_sorted.groupby('Item').agg(
    **{
        'Item type': ('Item type', 'last'),
        'Sales': ('Sales', 'sum')
    }
).reset_index()

print(result)

运行后输出符合预期:

ItemItem typeSales
AppleFruit17

为什么之前用last()没效果?

你之前直接用groupby().last()出错,是因为没有提前按日期排序。last()默认取的是原DataFrame中该组的最后一行,而非最新日期的行。只要先按日期把每组记录排好序,last()就能准确拿到最新日期对应的Item type。

另外也可以用lambda函数直接取每组日期最大的行对应的Item type,无需提前排序,但可读性稍差:

result = df.groupby('Item').agg(
    **{
        'Item type': lambda x: x.loc[df.loc[x.index, 'Date'].idxmax()],
        'Sales': 'sum'
    }
).reset_index()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 02:58:15