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

如何在Pandas中基于指定规则生成累积计算的结果列?

解决方案

首先,你的需求核心是根据行的位置偏移量生成线性递增的result列,以下是几种简洁高效的实现方式:

方法一:利用行索引计算偏移量(最通用)

通过当前行索引与首行索引的差值作为偏移量,无需依赖行的位置顺序,适用性更强:

import pandas as pd

# 构造你的原始DataFrame
df = pd.DataFrame(
    {'value': [109, 110, 111, 110, 108, 106, 100]},
    index=[10, 11, 12, 13, 14, 15, 16]
)

# 计算每行相对于首行的偏移量
offset = df.index - df.index[0]
# 生成result列
df['result'] = 109 + 0.05 * offset

执行后得到的DataFrame完全符合要求:

indexvalueresult
10109109.00
11110109.05
12111109.10
13110109.15
14108109.20
15106109.25
16100109.30

方法二:用序列生成偏移量(适合连续行)

如果你的行是连续排列的,直接用np.arange生成从0开始的序列作为偏移量:

import numpy as np

df['result'] = 109 + 0.05 * np.arange(len(df))

修正你的循环实现

你的原代码存在两个问题:

  1. speed = 0,05在Python中会被解析为元组,而非浮点数,应改为speed = 0.05
  2. 未初始化首行的result值,导致后续计算报错

修正后的循环代码如下:

df = pd.DataFrame(
    {'value': [109, 110, 111, 110, 108, 106, 100]},
    index=[10, 11, 12, 13, 14, 15, 16]
)

result = {}
speed = 0.05
first_index = df.index[0]
# 初始化首行结果
result[first_index] = 109
counter = 1

# 遍历后续行索引
for idx in df.index[1:]:
    result[idx] = result[first_index] + speed * counter
    counter += 1

# 将结果映射到DataFrame
df['result'] = df.index.map(result)

内容的提问来源于stack exchange,提问作者Igor K.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 20:18:20