How to find the cumsum of a column?

Viewed 918
dict={"asset":["S3","S2","E4","E1","A6","A8"],
"Rank":[1,2,3,4,5,6],"number_of_attributes":[2,1,2,2,1,1],
"number_of_cards":[1,2,2,1,2," "],"cards_plus1":[2,3,3,2,3," "]}

dframe=pd.DataFrame(dict,index=[1,2,3,4,5,6],
columns=["asset","Rank","number_of_attributes","number_of_cards","cards_plus1"])

i want to do cumsum of the column "cards_plus1". How can I do this? the output of the column cumsum should be that: 0 2 5 8 10 13

2 Answers

i want to start with zero instead of 2.. i want this outup : cards_plus1_cumsum 0 2 5 8 10 13

We can just pad a zero before the sums:

dframe["cumsum"] = np.pad(dframe["cards_plus1"][:-1].cumsum(), (1, 0), 'constant')

Try this:

First, replace the blank values by nan

import pandas as pd
import numpy as np

dict={"asset":["S3","S2","E4","E1","A6","A8"],"Rank":[1,2,3,4,5,6],"number_of_attributes":[2,1,2,2,1,1],
          "number_of_cards":[1,2,2,1,2," "],"cards_plus1":[2,3,3,2,3," "]}

dframe=pd.DataFrame(dict,index=[1,2,3,4,5,6],
columns=["asset","Rank","number_of_attributes","number_of_cards","cards_plus1"])

## replace blank values by nan
print(dframe.replace(r'^\s*$', np.nan, regex=True, inplace=True))

print (dframe)
>>> asset  Rank  number_of_attributes  number_of_cards  cards_plus1
1    S3     1                     2              1.0          2.0
2    S2     2                     1              2.0          3.0
3    E4     3                     2              2.0          3.0
4    E1     4                     2              1.0          2.0
5    A6     5                     1              2.0          3.0
6    A8     6                     1              NaN          NaN

Now the data type of the cards_plus1 column is object - change to numeric

### convert data type of the cards_plus1 to numeric 
dframe['cards_plus1'] = pd.to_numeric(dframe['cards_plus1'])

Now calculate cumulative sum

### now we can calculate cumsum
dframe['cards_plus1_cumsum'] = dframe['cards_plus1'].cumsum()

print(dframe)
>>>
asset  Rank  number_of_attributes  number_of_cards  cards_plus1  \
1    S3     1                     2              1.0          2.0   
2    S2     2                     1              2.0          3.0   
3    E4     3                     2              2.0          3.0   
4    E1     4                     2              1.0          2.0   
5    A6     5                     1              2.0          3.0   
6    A8     6                     1              NaN          NaN   

   cards_plus1_cumsum  
1                 2.0  
2                 5.0  
3                 8.0  
4                10.0  
5                13.0  
6                 NaN 

Instead of replacing the blank values by nan, you can replace them by zero, depends on what you want.. Hope this helped..

Related