我有一个数据框列,它有很多值,一些 +ve 和一些 -ve
V
-1
-4
-3
-2
+1
+2
+1
+5
-3
-1
+1
+4
-5
-2
-4
+4
+6
我想创建另一个列,它具有累积的特性
如果当前位置值与前一个值不同,则当前位置的累积值是当前值+前一个值
如果当前位置值与前一个值同号则当前位置的累加是前一个位置+当前值的累加
如图所示,value 为 V,cumulative 为 Cumulative
V Cumulative
-1 -1
-4 -5
-3 -8
-2 -10
+1 -1
+2 +1
+1 +2
+5 +7
-3 +2
-1 +1
+1 +0
+4 +4
-5 -1
-2 -3
-4 -7
+4 +0
+6 +6
正如您所看到的符号方向变化,它导致作为重置概念的累积变化
最佳答案
好问题:-),我把步骤分解了
# restore the value change(positive to negative) in and assign the group number , in the group you will only see all positive or negative.
df['g']=df.gt(0).diff().ne(0).cumsum()
# find the last value of the group
DF=df.groupby('g').last()
# shift the value to the next group , cause you need to carry save the value change
DF.index=DF.index+1
# combine the previous
df.groupby('g').V.cumsum()+df.g.map(DF.V).fillna(0)
Out[407]:
0 -1.0
1 -5.0
2 -8.0
3 -10.0
4 -1.0
5 1.0
6 2.0
7 7.0
8 2.0
9 1.0
10 0.0
11 4.0
12 -1.0
13 -3.0
14 -7.0
15 0.0
16 6.0
dtype: float64
分配新列后
df['cumlative']=df.groupby('g').V.cumsum()+df.g.map(DF.V).fillna(0)
df
Out[409]:
V g cumlative
0 -1 1 -1.0
1 -4 1 -5.0
2 -3 1 -8.0
3 -2 1 -10.0
4 1 2 -1.0
5 2 2 1.0
6 1 2 2.0
7 5 2 7.0
8 -3 3 2.0
9 -1 3 1.0
10 1 4 0.0
11 4 4 4.0
12 -5 5 -1.0
13 -2 5 -3.0
14 -4 5 -7.0
15 4 6 0.0
16 6 6 6.0
关于python - Pandas 累积符号概念,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47111443/