RGRGRG
RGRGRG

Reputation: 1079

Calculating rolling sums in Python

I have a data frame df with this format:

    Type     2013         2014          2015         2016          2017         
           EU  NO_EU    EU   NO_EU    EU  NO_EU    EU  NO_EU     EU  NO_EU               
     A      4     6      2     1       2    7       1    4        2    6    

     B      3     0      8     3       11   22      2    2        2    1   

and I want to create a new data frame with the rolling sums on 3-year period for both EU and NO_EU. Therefore, my new data frame should be like this:

           Type     2013         2014          2015         2016          2017         
                  EU  NO_EU    EU   NO_EU    EU  NO_EU    EU  NO_EU     EU  NO_EU     

            A      -     -      -      -      8    14      5    12       5    17     
            B      -     -      -      -      22   25      21   27       15   25      

The first two years will have no data since we have no enough data in order to calculate the sum for the last 3 years.

Any ideas on how can I do this in python? Maybe using something like the df.rolling(window=3).sum? My actual data frame has many rows and columns so I will use a loop in order to calculate them.

Thanks for any help in advance

Upvotes: 1

Views: 4338

Answers (1)

Space Impact
Space Impact

Reputation: 13255

You can try using rolling across axis=1 which is along columns, instead of rows axis=0.

df.rolling(window=3,axis=1).sum()

Upvotes: 1

Related Questions