当列Trade_Cost
为Buy(C)/Sell(V)
时,如何计算列C
的滚动总和,并在每次Current_Qntd
命中0
时重置该总和,然后开始新的滚动总和,直到下一个零?
Buy(C)/Sell(V) Qntd Price Current_Qntd Trade_Cost
0 C 33000 103.980000 33000 3.431340e+06
1 C 3682 102.940000 36682 3.790251e+05
2 C 108 103.490000 36790 1.117692e+04
3 C 10717 103.500000 47507 1.109210e+06
4 C 6831 103.760000 54338 7.087846e+05
5 C 968 107.000000 55306 1.035760e+05
6 C 32 107.000000 55338 3.424000e+03
7 V 3644 115.618296 51694 4.213131e+05
8 V 4704 115.995689 46990 5.456437e+05
9 V 46990 116.030000 0 5.452250e+06
10 C 35000 116.000000 35000 4.060000e+06
11 C 16000 117.999073 51000 1.887985e+06
12 V 1200 115.274742 49800 1.383297e+05
13 V 1400 116.700036 48400 1.633800e+05
14 V 23855 116.406567 24545 2.776879e+06
15 V 2589 116.247625 21956 3.009651e+05
16 V 12741 115.952801 9215 1.477355e+06
17 V 9132 115.951078 83 1.058865e+06
18 V 83 115.950000 0 9.623850e+03
编辑
我需要按资产分组,以下是上述DF的延续,每个DF代表不同的资产
Buy(C)/Sell(V) Qntd Price Current_Qntd Trade_Cost
0 C 100 114.290000 100 11429.000000
1 C 3137 115.020000 3237 360817.740000
2 V 100 114.500000 3137 11450.000000
3 V 1200 114.670000 1937 137604.000000
4 V 1937 115.000000 0 222755.000000
5 C 5586 96.790000 5586 540668.940000
6 V 5586 116.590000 0 651271.740000
7 C 971 118.630000 971 115189.730000
8 V 971 129.800000 0 126035.800000
9 C 600 126.416417 600 75849.850002
答案 0 :(得分:0)
IIUC,请尝试以下操作:
grp = (df['Current_Qntd'] == 0).cumsum()
df['Trade_Cost Sum'] = df['Trade_Cost'].mask(df['Buy(C)/Sell(V)'] != 'C', 0)
df['Trade_Cost Sum'] = df.groupby(grp)['Trade_Cost Sum'].cumsum()
df
输出:
Buy(C)/Sell(V) Qntd Price Current_Qntd Trade_Cost Trade_Cost Sum
0 C 33000 103.980000 33000 3431340.00 3431340.00
1 C 3682 102.940000 36682 379025.10 3810365.10
2 C 108 103.490000 36790 11176.92 3821542.02
3 C 10717 103.500000 47507 1109210.00 4930752.02
4 C 6831 103.760000 54338 708784.60 5639536.62
5 C 968 107.000000 55306 103576.00 5743112.62
6 C 32 107.000000 55338 3424.00 5746536.62
7 V 3644 115.618296 51694 421313.10 5746536.62
8 V 4704 115.995689 46990 545643.70 5746536.62
9 V 46990 116.030000 0 5452250.00 0.00
10 C 35000 116.000000 35000 4060000.00 4060000.00
11 C 16000 117.999073 51000 1887985.00 5947985.00
12 V 1200 115.274742 49800 138329.70 5947985.00
13 V 1400 116.700036 48400 163380.00 5947985.00
14 V 23855 116.406567 24545 2776879.00 5947985.00
15 V 2589 116.247625 21956 300965.10 5947985.00
16 V 12741 115.952801 9215 1477355.00 5947985.00
17 V 9132 115.951078 83 1058865.00 5947985.00
18 V 83 115.950000 0 9623.85 0.00