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

如何用Pandas创建首单元格公式不同的DataFrame并实现Ave Gain递归计算

问题1:创建首单元格公式与后续不同的DataFrame

最直观的方式是先单独处理首行,再通过循环计算后续行。这种方法逻辑清晰,新手也能快速理解:

import pandas as pd

# 第一步:构造示例原始数据(替换成你自己的数据集即可)
raw_data = {
    'Gain': [1.84, 1.62, 1.61, 0.89, 2.10],
    'Loss': [0.07, 0.12, 0.05, 0.20, 0.08]
}
df = pd.DataFrame(raw_data)

# 第二步:计算Ave Gain列
ave_gain_list = []
# 单独处理首单元格
first_ave_gain = (df['Gain'].iloc[0] + 0) / 2
ave_gain_list.append(first_ave_gain)
# 循环计算后续单元格:用上一个Ave值递推当前值
for current_gain in df['Gain'].iloc[1:]:
    prev_ave = ave_gain_list[-1]
    next_ave = (prev_ave + current_gain) / 2
    ave_gain_list.append(next_ave)
df['Ave Gain'] = ave_gain_list

# 第三步:同理计算Ave Loss列
ave_loss_list = []
first_ave_loss = (df['Loss'].iloc[0] + 0) / 2
ave_loss_list.append(first_ave_loss)
for current_loss in df['Loss'].iloc[1:]:
    prev_ave = ave_loss_list[-1]
    next_ave = (prev_ave + current_loss) / 2
    ave_loss_list.append(next_ave)
df['Ave Loss'] = ave_loss_list

# 查看最终结果
print(df)

运行后就能得到符合要求的DataFrame,首行和后续行的计算逻辑完全分离。


问题2:为Ave Gain创建递归计算表格

如果想更优雅地实现递推(递归)计算,可以用Python标准库的itertools.accumulate,它能高效处理累积递推逻辑,避免手动写循环:

from itertools import accumulate
import pandas as pd

# 沿用之前的原始数据
raw_data = {
    'Gain': [1.84, 1.62, 1.61, 0.89, 2.10],
    'Loss': [0.07, 0.12, 0.05, 0.20, 0.08]
}
df = pd.DataFrame(raw_data)

# 定义递归计算函数:输入前一个Ave值和当前Gain,返回下一个Ave值
def calculate_next_ave(prev_ave, current_gain):
    return (prev_ave + current_gain) / 2

# 计算Ave Gain:首单元格单独处理,后续用accumulate递推
initial_ave = (df['Gain'].iloc[0] + 0) / 2
# 从第二个Gain值开始,用accumulate自动完成递推计算
后续_ave_gain = list(accumulate(df['Gain'].iloc[1:], calculate_next_ave, initial=initial_ave))
# 合并首单元格和后续值
ave_gain_full = [initial_ave] + 后续_ave_gain
df['Ave Gain'] = ave_gain_full

# Ave Loss的递归计算逻辑完全一致,只需替换对应的列名
def calculate_next_loss_ave(prev_ave, current_loss):
    return (prev_ave + current_loss) / 2

initial_loss_ave = (df['Loss'].iloc[0] + 0) / 2
后续_ave_loss = list(accumulate(df['Loss'].iloc[1:], calculate_next_loss_ave, initial=initial_loss_ave))
ave_loss_full = [initial_loss_ave] + 后续_ave_loss
df['Ave Loss'] = ave_loss_full

print(df)

两种方法的对比

  • 手动循环:代码直白,方便调试和理解递推逻辑,小数据集下效率足够
  • accumulate:更简洁高效,底层是C实现,大数据集下性能优势明显

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:09:52