首页 > 解决方案 > 与熊猫的算术级数

问题描述

你好我有这个数据框

df = pd.DataFrame({'year': [1982, 1984, 1985, 1986, 1987, 1988, 1989, 1990], 'VB': [13215.8, 13215.8, 13215.8, 13215.8, 13215.8, 13215.8, 13215.8, 13215.8], 'coef': [0, 0.0814, 0.1213, 0.1380, 0.1601, 0.1906, 0.2355, 0.3080]})
   year       VB    coef
0  1982  13215.8  0.0000
1  1984  13215.8  0.0814
2  1985  13215.8  0.1213
3  1986  13215.8  0.1380
4  1987  13215.8  0.1601
5  1988  13215.8  0.1906
6  1989  13215.8  0.2355
7  1990  13215.8  0.3080

我想添加一个列'result' = VB - (previous 结果) * coef

结果的第一个值是VB = 13215.8

VB - (previous `result`) * coef

13215.8 - 13215.8 * 0.0814 = 12140.03 
13215.8 - 12140.03 * 0.1213 = 11743.21

等等 ...

标签: pythonpandas

解决方案


您可以像这样遍历行来完成您的目标:

result = df['VB'][0]
results = []
for _, row in df.iterrows():
    result = row['VB'] - result * row['coef']
    results.append(result)
df['results'] = results
print(df)

    year       VB    coef       results
0  1982  13215.8  0.0000  13215.800000
1  1984  13215.8  0.0814  12140.033880
2  1985  13215.8  0.1213  11743.213890
3  1986  13215.8  0.1380  11595.236483
4  1987  13215.8  0.1601  11359.402639
5  1988  13215.8  0.1906  11050.697857
6  1989  13215.8  0.2355  10613.360655
7  1990  13215.8  0.3080   9946.884918

推荐阅读