如何在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完全符合要求:
| index | value | result |
|---|---|---|
| 10 | 109 | 109.00 |
| 11 | 110 | 109.05 |
| 12 | 111 | 109.10 |
| 13 | 110 | 109.15 |
| 14 | 108 | 109.20 |
| 15 | 106 | 109.25 |
| 16 | 100 | 109.30 |
方法二:用序列生成偏移量(适合连续行)
如果你的行是连续排列的,直接用np.arange生成从0开始的序列作为偏移量:
import numpy as np df['result'] = 109 + 0.05 * np.arange(len(df))
修正你的循环实现
你的原代码存在两个问题:
speed = 0,05在Python中会被解析为元组,而非浮点数,应改为speed = 0.05- 未初始化首行的
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.
相关产品推荐
相关产品推荐

