我有一个包含 3 列的数据框。
Date Close pos_chg cash
2000-01-04 81.9375 0.0 10000.00
2000-01-05 69.7500 0.0 0.00
2000-01-06 65.5625 0.0 0.00
2000-01-07 69.5625 0.0 0.00
2000-01-10 69.1875 100.0 0.00
2000-01-11 66.7500 0.0 0.00
2000-01-12 63.5625 -200.0 0.00
2000-01-13 65.9375 200.0 0.00
2000-01-14 64.2500 -200.0 0.00
2000-01-18 64.1250 0.0 0.00
我想计算什么。
Date Close pos_chg cash
2000-01-04 81.9375 0.0 10000.00
2000-01-05 69.7500 0.0 10000.00
2000-01-06 65.5625 0.0 10000.00
2000-01-07 69.5625 0.0 10000.00
2000-01-10 69.1875 100.0 3081.25
2000-01-11 66.7500 0.0 3081.25
2000-01-12 63.5625 -200.0 15793.75
2000-01-13 65.9375 200.0 2606.25
2000-01-14 64.2500 -200.0 15456.25
2000-01-18 64.1250 0.0 15456.25
我认为这段代码可以工作。
df['cash']=df['cash'].shift(1)-(df['pos_chg']*df['Close'])
感谢任何帮助。
最佳答案
代码:
df['delta_cash'] = (df.Close * -df.pos_chg + df.cash).cumsum()
测试代码:
import pandas as pd
import numpy as np
df = pd.read_fwf(StringIO(u"""
Date Close pos_chg cash
2000-01-04 81.9375 0.0 10000.00
2000-01-05 69.7500 0.0 0.00
2000-01-06 65.5625 0.0 0.00
2000-01-07 69.5625 0.0 0.00
2000-01-10 69.1875 100.0 0.00
2000-01-11 66.7500 0.0 0.00
2000-01-12 63.5625 -200.0 0.00
2000-01-13 65.9375 200.0 0.00
2000-01-14 64.2500 -200.0 0.00
2000-01-18 64.1250 0.0 0.00"""),
skiprows=1)
df['delta_cash'] = (df.Close * -df.pos_chg + df.cash).cumsum()
print(df)
结果:
Date Close pos_chg cash delta_cash
0 2000-01-04 81.9375 0.0 10000.0 10000.00
1 2000-01-05 69.7500 0.0 0.0 10000.00
2 2000-01-06 65.5625 0.0 0.0 10000.00
3 2000-01-07 69.5625 0.0 0.0 10000.00
4 2000-01-10 69.1875 100.0 0.0 3081.25
5 2000-01-11 66.7500 0.0 0.0 3081.25
6 2000-01-12 63.5625 -200.0 0.0 15793.75
7 2000-01-13 65.9375 200.0 0.0 2606.25
8 2000-01-14 64.2500 -200.0 0.0 15456.25
9 2000-01-18 64.1250 0.0 0.0 15456.25
关于python - 对数据帧列前一行和两列的乘积求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48000395/