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] })
核心步骤
确定目标日期列
直接取最后一个非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)计算指定日期前的总和
取Codes之后、目标日期列之前的所有数值列,按行求和:df['total_before'] = df.iloc[:, 1:target_col_index].sum(axis=1)计算指定日期后的总和
取目标日期列之后的所有数值列,按行求和: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
相关产品推荐
相关产品推荐

