python - 与熊猫的算术级数
问题描述
你好我有这个数据框
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
等等 ...
解决方案
您可以像这样遍历行来完成您的目标:
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
推荐阅读
- sql-server - TSQL中嵌套sp调用中创建的临时表的范围和寿命
- python - django 不会从 statifiles_dirs 加载静态文件
- android - 我安装了 intel HAXM 并在 BIOS 中启用了虚拟技术,但仍然无法运行模拟器
- python - 一元运算符“如果 x 为 2,则 ~x == -3”
- javascript - Flask,Ajax,获取 ajax url 的 url 值
- php - 如何用php中的模式替换所有出现的字符串开始和结束
- python-3.x - VS CODE 中没有终端输出
- mysql - 在满足其他条件后,MySQL SELECT 具有条件的最小行 ID
- c++ - Qt:无法直接将滚动条添加到有孩子的小部件
- java - java蚂蚁应用程序。linux下无法编译