Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine pivot with cumulative sum in Pandas

I have a simple dataframe:

   type  | code | date    |value

0  apple | ap1  |08/12/14 |2
1  apple | ap1  |09/12/14 |12
2  apple | ap1  |10/12/14 |4
3  banana| b1   |08/12/14 |5
4  banana| b1   |09/12/14 |67
5  banana| b1   |10/12/14 |77
6  orange| o1   |08/12/14 |21
7  orange| o1   |09/12/14 |1
8  orange| o1   |10/12/14 |16

Which i can easily pivot with the dates as columns using the following function:

pivot = pd.pivot_table(data,values=('value'),rows=['code','type'],cols='date',aggfunc=np.sum)

However I cant find a way to use a cumulative sum in place of the np.sum, I would like to display the data in the following format? Is this possible?

type    08/12/14    09/12/14    10/12/14
apple   2           12          4
banana  7           79          81
orange  28          80          97
like image 930
user636322 Avatar asked Nov 25 '25 20:11

user636322


1 Answers

Pandas is great, with a little help from a friend this is done by simply adding the following line:

pivot=pivot.cumsum()
like image 77
user636322 Avatar answered Nov 28 '25 12:11

user636322



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!