簡體   English   中英

熊貓累計標志概念

[英]Pandas Cumulative on sign concept

我有一個dataframe列,它有很多值,一些+ ve和一些-ve

 V
-1
-4
-3
-2
+1
+2
+1
+5
-3
-1
+1
+4
-5
-2
-4
+4
+6

我想創建另一列,該列具有累積性

如果當前位置值與先前位置的符號不同,則當前位置的累計值為當前值+先前值

如果當前位置值與前一個位置具有相同的符號,則當前位置的累加即為前一個位置的累加+當前值

值是V,累計是累積,如圖所示

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

步驟1.定義變量和輔助函數

sum_p = 0 # sum previous
value_p = 0 # value previous
sign_p = "-"

def sign(x):
    return("+" if x>0 else "-")

df = pd.DataFrame({"V": df.V, "Cumulative":0}, columns = ["V","Cumulative"])

步驟2.計算累計

for i in df.iterrows():
    if sign(i[1][0]) == sign_p:
        df.iloc[i[0],1] = sum_p + i[1][0]
    else:
        df.iloc[i[0],1] = value_p + i[1][0]
    sum_p = i[1][1]
    value_p = i[1][0]
    sign_p = sign(i[1][0])

df
    V   Cumulative
0   -1  -1
1   -4  -5
2   -3  -8
3   -2  -10
4   1   -1
5   2   1
6   1   2
7   5   7
8   -3  2
9   -1  1
10  1   0
11  4   4
12  -5  -1
13  -2  -3
14  -4  -7
15  4   0
16  6   6

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM