python - 递归地将公式应用于pandas中的行,必须从上面的行中获取值
问题描述
输入 df1
Initial value=8
Id rating Learnrate formula
1 2 0.1 7.4
2 3 0.2 6.52
3 4 0.1
对于第一排
formula=Initial value*(1-Learnrate)+rating*Learnrate
=8*(1-0.1)+2*0.1=7.2+0.2=7.4
从第 2 行开始取上一行公式值 = 7.4
=7.4*(1-0.2)+3*0.2=6.52
解决方案
您可以计算第一行(就像您在问题中所做的那样)并遍历其余行以使用前一行的值计算每个公式。
#calculate the first row using formula and initial value
df1.loc[0, 'formula'] = Initial value*(1-df1.loc[0, 'Learnrate'])+df1.loc[0, 'rating']*df1.loc[0, 'Learnrate']
#Loop through rows and calculate each formula for row i value using previous value of formula in row i-1
for i in range(1, len(df1)):
df1.loc[i, 'formula'] = df1.loc[i-1, 'formula']*(1-df1.loc[i, 'Learnrate'])+df1.loc[i, 'rating']*df1.loc[i, 'Learnrate']
推荐阅读
- php - 如何存储管理员帐户可以在 PHP 中更改的应用程序设置?
- makefile - 为什么不让合并模式规则成为先决条件,我该如何做到这一点?
- css - How can I remove the white-space around the numbers on a JS timer?
- python - 为什么在调整窗口大小时 tkinter.Tk.update() 会阻塞?
- java - 无法使用 Jar 文件找到或加载主类。原因是 bcprov-jdk15-133
- python - 如何在 Windows 平台的 PCI 配置寄存器(空间)中访问或获取数据(比特流)
- javascript - 关于自定义 React modal 组件的一个小问题
- ruby-on-rails - 我如何知道要编辑哪个文件以及从该错误消息中执行什么操作?
- java - 如何用单个正则表达式模式替换过多的 SQL 通配符?
- pandas - 使用 .loc 和 slice 设置时,日期时间列强制为 int