Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?(当在应用中也计算前一个值时,Pandas 中是否可以使用 dataframe.apply 中的前一行值?)
问题描述
我有以下数据框:
Index_Date A B C D
===============================
2015-01-31 10 10 Nan 10
2015-02-01 2 3 Nan 22
2015-02-02 10 60 Nan 280
2015-02-03 10 100 Nan 250
要求:
Index_Date A B C D
===============================
2015-01-31 10 10 10 10
2015-02-01 2 3 23 22
2015-02-02 10 60 290 280
2015-02-03 10 100 3000 250
Column C 是通过取 D 的 value 为 2015-01-31 派生的.
Column C is derived for 2015-01-31 by taking value of D.
那我需要将C的value用于2015-01-31并乘以value A 在 2015-02-01 并添加 B.
Then I need to use the value of C for 2015-01-31 and multiply by the value of A on 2015-02-01 and add B.
我尝试了一个 apply 和一个 shift 使用一个 if else 这给出了一个关键错误.
I have attempted an apply and a shift using an if else by this gives a key error.
推荐答案
首先,创建派生值:
df.loc[0, 'C'] = df.loc[0, 'D']
然后遍历剩余的行并填充计算值:
Then iterate through the remaining rows and fill the calculated values:
for i in range(1, len(df)):
df.loc[i, 'C'] = df.loc[i-1, 'C'] * df.loc[i, 'A'] + df.loc[i, 'B']
Index_Date A B C D
0 2015-01-31 10 10 10 10
1 2015-02-01 2 3 23 22
2 2015-02-02 10 60 290 280
这篇关于当在应用中也计算前一个值时,Pandas 中是否可以使用 dataframe.apply 中的前一行值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当在应用中也计算前一个值时,Pandas 中是否可以使用 dataframe.apply 中的前一行值?
基础教程推荐
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
