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

如何用Python按客户提取最早订单日期并保存为新DataFrame

问题

现有如下Pandas DataFrame:

import pandas as pd
df = pd.DataFrame({"customer": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"],
                   "order_date": ["12-12-2022", "12-12-2020", "12-12-2019", "12-12-2018", "12-12-2022", "12-12-2022", "12-12-2015", "12-12-2019", "12-12-2017"]})

需要按每个客户提取最早的订单日期(即最小值),并保存为新的DataFrame,期望输出如下:

customer 1st_order_date
0       foo      12-12-2018
1       bar      12-12-2015

解决方案

方法一:直接分组聚合

这是最简洁的实现方式,直接按customer分组后对order_date取最小值,再调整列名和索引:

# 分组计算每个客户的最早订单日期
result = df.groupby('customer')['order_date'].min().reset_index()
# 重命名列名为需求的格式
result.rename(columns={'order_date': '1st_order_date'}, inplace=True)
# 查看结果
print(result)

方法二:先标准化日期格式(更严谨)

如果order_date的字符串格式不统一,直接取最小值可能出错。建议先转换为日期类型,计算后再转回目标字符串格式:

# 将字符串类型的日期转换为datetime格式
df['order_date'] = pd.to_datetime(df['order_date'], format='%d-%m-%Y')
# 分组取最早日期,再转回原字符串格式
result = df.groupby('customer')['order_date'].min().dt.strftime('%d-%m-%Y').reset_index()
# 重命名列名
result.rename(columns={'order_date': '1st_order_date'}, inplace=True)
# 查看结果
print(result)

内容的提问来源于stack exchange,提问作者Beginner in the house

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 13:05:54