首页 > 解决方案 > 递归地将公式应用于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

标签: pythonpandas

解决方案


您可以计算第一行(就像您在问题中所做的那样)并遍历其余行以使用前一行的值计算每个公式。

#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']

推荐阅读