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

如何修改循环获取Pandas DataFrame中各产品最后销售日期

问题描述

我有一个Pandas DataFrame(变量名df),包含各类产品信息及特定月份的销售记录,数据如下:

product  2021-01-01 00:00:00  2021-02-01 00:00:00  2021-03-01 00:00:00  2021-04-01 00:00:00  2021-05-01 00:00:00  2021-06-01 00:00:00  2021-07-01 00:00:00  2021-08-01 00:00:00  2021-09-01 00:00:00  2021-10-01 00:00:00  2021-11-01 00:00:00  2021-12-01 00:00:00  2022-01-01 00:00:00  2022-02-01 00:00:00  2022-03-01 00:00:00  2022-04-01 00:00:00  2022-05-01 00:00:00  2022-06-01 00:00:00  2022-07-01 00:00:00  2022-08-01 00:00:00
2          C                    1                    1                    1                    1                    1                    1                    1                    1                    1                    0                    0                    0                    0                    0                    0                    0                    0                    0                    0                    0
3          D                    1                    1                    1                    1                    1                    1                    1                    1                    1                    1                    1                    1                    1                    0                    0                    0                    0                    0                    0                    0

我需要获取每个产品最后一次有销售的日期,比如产品C的最后销售日期是2021-10-01,产品D是2022-02-01。

我运行了以下循环代码,但它返回了所有销量大于0的日期:

for col in df.iloc[:,1:].columns:
    for val in df[col]:
        if val>0:
            print(col)

请问如何调整这个循环,使其仅返回每个产品对应的最后一个符合条件的日期?

解决方案

方式一:调整原循环实现

原循环的问题是遍历所有列和值,只要有销售就打印日期,没有针对每个产品跟踪最后有效日期。可以改为按行遍历每个产品,然后倒序检查日期列,找到第一个值为1的日期(即最后一次销售日期):

# 遍历每一行(每个产品)
for idx, row in df.iterrows():
    product = row['product']
    # 倒序遍历日期列,找到第一个值为1的日期
    for col in reversed(df.columns[1:]):
        if row[col] > 0:
            # 提取日期部分(去掉时间戳)
            print(f"产品{product}的最后销售日期:{col.split(' ')[0]}")
            break

运行后输出:

产品C的最后销售日期:2021-10-01
产品D的最后销售日期:2022-02-01

方式二:Pandas矢量化方法(更高效)

用循环处理Pandas数据并非最优方案,推荐用矢量化操作直接计算,代码更简洁且处理大数据时效率更高:

import pandas as pd

# 将日期列转为datetime类型(确保日期可排序)
date_cols = df.columns[1:]
# 转换销售值为数值类型
df[date_cols] = df[date_cols].apply(pd.to_numeric)
# 转换列名为datetime对象
date_cols_dt = pd.to_datetime(date_cols)

# 对每个产品,筛选出有销售的日期并取最大值(最后一次)
last_sale_dates = df.set_index('product')[date_cols].apply(
    lambda x: date_cols_dt[x == 1].max(), axis=1
)

# 打印结果
print(last_sale_dates)

输出结果:

product
C   2021-10-01
D   2022-02-01
dtype: datetime64[ns]

如果需要格式化输出为字符串日期,可追加:

print(last_sale_dates.dt.strftime('%Y-%m-%d'))

内容的提问来源于stack exchange,提问作者Maksim .Levin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:25:38