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

Python实现DataFrame按指定日期(末表头)计算每行前后数值求和

解决方法

先模拟符合你描述的DataFrame结构:

import pandas as pd

# 示例数据
df = pd.DataFrame({
    'Codes': ['X1', 'X2', 'X3'],
    '2022-10-01': [5, 12, 8],
    '2022-11-01': [7, 9, 15],
    '2022-12-01': [10, 6, 11],  # 最后一个日期(你的指定日期)
    '2023-01-01': [3, 14, 4],
    '2023-02-01': [8, 5, 9]
})

核心步骤

  1. 确定目标日期列
    直接取最后一个非Codes的列作为指定日期:

    # 筛选出所有日期列
    date_columns = [col for col in df.columns if col != 'Codes']
    # 目标日期是最后一个表头
    target_date_col = date_columns[-1]
    # 获取该列在DataFrame中的位置索引
    target_col_index = df.columns.get_loc(target_date_col)
    
  2. 计算指定日期前的总和
    取Codes之后、目标日期列之前的所有数值列,按行求和:

    df['total_before'] = df.iloc[:, 1:target_col_index].sum(axis=1)
    
  3. 计算指定日期后的总和
    取目标日期列之后的所有数值列,按行求和:

    df['total_after'] = df.iloc[:, target_col_index+1:].sum(axis=1)
    

自定义扩展

如果需要把指定日期本身的数值算入总和,只需要调整切片范围:

# 把目标日期算入前总和
df['total_before_include_target'] = df.iloc[:, 1:target_col_index+1].sum(axis=1)
# 把目标日期算入后总和
df['total_after_include_target'] = df.iloc[:, target_col_index:].sum(axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 02:19:57