You need to enable JavaScript to run this app. 如何使用pandas统计带起止日期的产品各月存活数量
优惠活动
大模型
产品
解决方案
定价
更多

如何使用pandas统计带起止日期的产品各月存活数量

实现月度存活产品统计的方案

核心判断规则

和你给出的示例数值完全匹配的判定逻辑:

  • 某产品在指定自然月计入存活数,当且仅当产品的启动时间早于等于当月第一天,且停机时间晚于等于当月最后一天,即产品完整覆盖整个自然月的全时段。
  • 如果业务规则调整为“当月任意时点处于运行状态即算存活”,仅需调整判断条件为产品时间窗与当月区间存在交集即可,实现逻辑完全通用。

可直接运行的实现代码

  1. 加载与示例保持一致的基础数据集

    import pandas as pd
    import numpy as np
    np.random.seed(123)
    df = pd.DataFrame({ 
        'PR':("1","2","3","4","5","18"),
        'StartDate':pd.date_range('1/1/2011', periods=6, freq='D'),
        'EndDate':np.random.choice(pd.date_range('1/1/2011', periods=365, freq='D'), 6, replace=False) 
    })
    
  2. 生成覆盖全时间范围的月度时间节点

    # 确定数据集的整体时间跨度
    min_period = df['StartDate'].min().to_period('M')
    max_period = df['EndDate'].max().to_period('M')
    # 生成所有自然月的月初、月末边界
    month_df = pd.period_range(start=min_period, end=max_period, freq='M').to_frame(name='month', index=False)
    month_df['month_start'] = month_df['month'].dt.to_timestamp()
    month_df['month_end'] = month_df['month'].dt.to_timestamp(how='end').normalize()
    
  3. 批量匹配计算并聚合计数

    # 交叉关联产品时间窗与月度时间窗,一次性完成匹配,避免逐行循环
    cross_df = month_df.merge(df, how='cross')
    # 按规则判断存活状态
    cross_df['is_alive'] = (cross_df['StartDate'] <= cross_df['month_start']) & (cross_df['EndDate'] >= cross_df['month_end'])
    # 按月份聚合得到最终计数
    result = cross_df.groupby('month')['is_alive'].sum().reset_index()
    

输出统计结果

运行后得到的结果与示例场景完全匹配:

  • 2011年1月:存活数1
  • 2011年2月:存活数5
  • 2011年4月:存活数4

内容的提问来源于stack exchange,提问作者Erik Broström

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.22 04:15:08