Robby star
Robby star

Reputation: 279

CUMSUM addition as below

i have to calculate the cumsum addition in the below. A should be blank. B should be as it, c should 31 + 30 = 61, previous item and addition of present item, D = 61 + 31 = 92 and so on.

data:

    0   1   cumsum

1   A   31  
2   B   31  31
3   C   30  61
4   D   31  92
5   E   30  122
6   F   31  153
7   G   31  184
8   H   30  214
9   I   31  245
10  J   30  276

my code: 
data['cumsum'] = data[1].cumsum() 
data

    0   1   cumsum
1   A   31  31
2   B   31  61
3   C   30  92
4   D   31  122
5   E   30  153
6   F   31  184
7   G   31  214
8   H   30  245
9   I   31  276
10  J   30  306

i need the expected output as below:

0   1   cumsum

1   A   31  
2   B   31  31
3   C   30  61
4   D   31  92
5   E   30  122
6   F   31  153
7   G   31  184
8   H   30  214
9   I   31  245
10  J   30  276

my code: 
data['cumsum'] = data[1].cumsum() 
data

Upvotes: 0

Views: 42

Answers (2)

piRSquared
piRSquared

Reputation: 294258

If you use iloc to accomplish the offset, you don't need to shift back as Pandas will align the indices.

df.iloc[1:, 1].cumsum()

2      31
3      61
4      92
5     122
6     153
7     184
8     214
9     245
10    275
Name: 1, dtype: int64

Then use assign to create the new column.

df.assign(cumsum=df.iloc[1:, 1].cumsum())

    0   1  cumsum
1   A  31     NaN
2   B  31    31.0
3   C  30    61.0
4   D  31    92.0
5   E  30   122.0
6   F  31   153.0
7   G  31   184.0
8   H  30   214.0
9   I  31   245.0
10  J  30   275.0

Upvotes: 0

BENY
BENY

Reputation: 323226

I think you need

df['1'].shift(-1).cumsum().shift(1)

1       NaN
2      31.0
3      61.0
4      92.0
5     122.0
6     153.0
7     184.0
8     214.0
9     245.0
10    275.0
Name: 1, dtype: float64

Upvotes: 3

Related Questions