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

基于colum_start与colum_stop的Pandas动态列范围求和需求

解决方案

要实现每行根据colum_start和colum_stop指定的列范围求和,可按以下步骤操作:

步骤1:修正列名(处理空格问题)

你的数据中colum_start列名带有末尾空格,先统一列名避免后续出错:

df = df.rename(columns={'colum_start ': 'colum_start'})

步骤2:提取日期列列表

获取所有需要参与求和的日期列,确保顺序与DataFrame中一致:

date_cols = [col for col in df.columns if col.startswith('2021')]
# 也可通过位置索引提取:date_cols = df.columns[2:-2].tolist()

步骤3:定义行求和函数并应用

编写函数处理每行的范围求和,再用apply逐行计算:

def calculate_row_sum(row):
    # 将start/stop转为字符串(匹配列名格式)
    start_col = str(row['colum_start'])
    stop_col = str(row['colum_stop'])
    
    # 获取列的索引位置
    start_idx = date_cols.index(start_col)
    stop_idx = date_cols.index(stop_col)
    
    # 对指定范围的列求和
    return row[date_cols[start_idx:stop_idx+1]].sum()

# 生成sum_column列
df['sum_column'] = df.apply(calculate_row_sum, axis=1)

最终结果验证

运行后sum_column的结果如下:

NameIDsum_column
AppleF164
BananaF136
OrangeF147
CherryF1132
EggV172
CheeseV210

大数据量优化方案

如果数据量较大,apply效率偏低,可改用向量化操作提升速度:

import numpy as np

# 将日期列转为numpy数组
date_vals = df[date_cols].values
# 构建列名到索引的映射
col_index_map = dict(zip(date_cols, range(len(date_cols))))
# 获取每行start/stop的索引
start_indices = df['colum_start'].astype(str).map(col_index_map)
stop_indices = df['colum_stop'].astype(str).map(col_index_map)

# 生成掩码矩阵,标记每行需要求和的列
mask = np.zeros_like(date_vals, dtype=bool)
for i, (s, e) in enumerate(zip(start_indices, stop_indices)):
    mask[i, s:e+1] = True

# 计算求和
df['sum_column'] = (date_vals * mask).sum(axis=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 06:43:09