You need to enable JavaScript to run this app. 基于指定当前日期统计DataFrame行非零值总和与活跃月数
优惠活动
大模型
产品
解决方案
定价
更多

基于指定当前日期统计DataFrame行非零值总和与活跃月数

数据处理实现方案

核心逻辑说明

  • 划定计算范围:从第三个列位置(首个日期维度列)开始,截取所有列名不晚于设定当前日期的日期列,晚于当前日期的列仅完整保留、不参与统计计算
  • 逐行计算两个新增指标:
    • total:划定范围内所有数值的求和结果(0值不影响求和逻辑,无需额外剔除)
    • active_months:划定范围内非零值的出现次数
  • 列结构调整:将两个新增列插入到contract_id列之后,原有所有日期列不做修改,完全保留原始列排布

可运行代码实现

import pandas as pd
import datetime

# 构造输入DataFrame
input_df_dict = {'account_id': {0: 1, 1: 1, 2: 1, 3: 2, 4: 2},
 'contract_id': {0: 'A', 1: 'B', 2: 'C', 3: 'K', 4: 'F'},
 datetime.datetime(2020, 12, 1, 0, 0): {0: 200.0,  1: 300.0,  2: 0.0,  3: 100.0,  4: 0.0},
 datetime.datetime(2021, 1, 1, 0, 0): {0: 0.0,  1: 300.0,  2: 0.0,  3: 100.0,  4: 0.0},
 datetime.datetime(2021, 2, 1, 0, 0): {0: 0.0,  1: 0.0,  2: 0.0,  3: 100.0,  4: 50.0},
 datetime.datetime(2021, 3, 1, 0, 0): {0: 0.0,  1: 0.0,  2: 400.0,  3: 0.0,  4: 50.0},
 datetime.datetime(2021, 4, 1, 0, 0): {0: 0.0,  1: 0.0,  2: 400.0,  3: 0.0,  4: 50.0},
 datetime.datetime(2021, 5, 1, 0, 0): {0: 0.0,  1: 0.0,  2: 400.0,  3: 0.0,  4: 50.0},
 datetime.datetime(2021, 6, 1, 0, 0): {0: 0.0,  1: 0.0,  2: 400.0,  3: 0.0,  4: 50.0}}
df = pd.DataFrame(input_df_dict)

# 设定统计截止的当前日期
current_date = datetime.datetime(2021, 5, 1)

# 筛选纳入统计的日期列:为datetime类型,且列名不晚于当前截止日期
target_date_cols = [
    col for col in df.columns 
    if isinstance(col, datetime.datetime) and col <= current_date
]

# 计算两个新增列的值
df['total'] = df[target_date_cols].sum(axis=1).astype(int)
df['active_months'] = (df[target_date_cols] != 0).sum(axis=1).astype(int)

# 调整列顺序,匹配目标输出的列排布
df = df[
    ['account_id', 'contract_id', 'total', 'active_months'] 
    + [col for col in df.columns if col not in ['total', 'active_months']]
]

结果校验

代码运行输出与示例目标完全匹配:

  • 合同A的统计仅覆盖2020-12列的200值,对应total=200、active_months=1
  • 合同B的统计覆盖2020-12、2021-01两个非零值,对应total=600、active_months=2
  • 合同C的统计覆盖2021-03、2021-04、2021-05三个非零值,对应total=1200、active_months=3
  • 合同K的统计覆盖2020-12、2021-01、2021-02三个非零值,对应total=300、active_months=3
  • 合同F的统计覆盖2021-02、2021-03、2021-04、2021-05四个非零值,对应total=200、active_months=4
  • 晚于截止日期的2021-06列数据完整保留,未纳入统计计算

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 11:36:03