Search code examples
pythondataframecumsum

How to find the cumsum of a column?


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


Solution

  • 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')