foreignvol
foreignvol

Reputation: 701

Pandas Cumsum skip rows

I have a dataframe like the following.

idx vals
0   10
1   21
2   12
3   33
4   14
5   55
6   16
7   77

I would like to perform a cumsum (and avoid a for) but only considering rows with the same idx mod 2. For instance, for row 3 I would like to obtain 21+33=54, while for row 4, 10+12+14 = 36.

Any ideas?

Upvotes: 3

Views: 391

Answers (1)

BENY
BENY

Reputation: 323306

You just need groupby here

df.vals.groupby(df.idx%2).cumsum()
Out[75]: 
0     10
1     21
2     22
3     54
4     36
5    109
6     52
7    186
Name: vals, dtype: int64

Upvotes: 5

Related Questions