python - 使用以前的行进行迭代
问题描述
如何使用迭代类型的规则创建 col2?
col2 = col1 + 0.1(col2's previous value). If there is no previous value (here in 20 Dec 2019), then col2 should equal col1
df
date col1
2019-12-20 10
2019-12-27 3
2020-01-03 7
预期产出
date col1 col2
2019-12-20 10 10 (no previous value, so equal col1)
2019-12-27 3 4 (3+0.1*10)
2020-01-03 7 7.4 (7+0.1*4)
解决方案
使用np.cumsum
(受@MustafaAydın 公式的启发)
p = 0.1 ** np.arange(len(df)-1, -1, -1)
df['col2'] = np.cumsum(p * df['col1']) / p
>>> df
date col1 col2
0 2019-12-20 10 10.0
1 2019-12-27 3 4.0
2 2020-01-03 7 7.4
推荐阅读
- apache-spark - Scala Spark:为 json 找到多个来源
- python - Django 服务器不为管理页面提供静态文件
- python - 我试图将图像附加到我的电子邮件发件人写的 python
- java - 获取 mysql(innodb) AUTO_INCREMENT Column、JDBC/getGeneratedKeys()/last_insert_id (in OkPacket) 和 LAST_INSERT_ID() 的方法
- javascript - Cloudflare Workers 主 URL 重定向不起作用,参数也不起作用
- python - Python 无法识别来自外部代码的 txt 文件
- php - 如何配置 symfony check:requirements?
- mysql - 从带有 unicode 字符的表中选择时 Hibernate + Mysql 语法错误
- java - 在 Java 中,当 JSON 的结构不同时,如何屏蔽 JSON 的所有匹配键的值?
- python - Errno 36:解析python XML时文件名太长错误