How To Reset Cumsum After Change In Sign Of Values?
In [46]: d = np.random.randn(10, 1) * 2 In [47]: df = pd.DataFrame(d.astype(int), columns=['data']) I am trying to create a cumsum column where it should reset after a sign chang
Solution 1:
Create new key to groupby
, then do cumsum
within each group
New key Create: By using the sign change , if change we add one then it will belong to nest group
df.groupby(df.data.lt(0).astype(int).diff().ne(0).cumsum()).data.cumsum()
Out[798]:
0 -21 -3213 -34 -45262758 -19 -3
Name: data, dtype: int64
Post a Comment for "How To Reset Cumsum After Change In Sign Of Values?"