Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing up previous 10 rows of a dataframe

I'm wondering how to sum up 10 rows of a data frame from any point.

I tried using rolling(10,window =1).sum() but the very first row should sum up the 10 rows below. Similar issue with cumsum()

So if my data frame is just the A column, id like it to output B.

    A   B
0   10  550
1   20  650
2   30  750
3   40  850
4   50  950
5   60  1050
6   70  1150
7   80  1250
8   90  1350
9   100 1450
10  110 etc
11  120 etc
12  130 etc
13  140 
14  150 
15  160 
16  170 
17  180 
18  190 

It would be similar to doing this operation in excel and copying it down

Excel Example:

Excel Example

like image 427
novawaly Avatar asked Jul 16 '18 14:07

novawaly


People also ask

How do I get last 10 rows in a DataFrame?

Use pandas. DataFrame. tail(n) to get the last n rows of the DataFrame. It takes one optional argument n (number of rows you want to get from the end).

How do I sum multiple rows in a data frame?

To sum all the rows of a DataFrame, use the sum() function and set the axis value as 1. The value axis 1 will add the row values.

How do you get the sum of rows in pandas?

The sum() method adds all values in each column and returns the sum for each column. By specifying the column axis ( axis='columns' ), the sum() method searches column-wise and returns the sum of each row.

How do you sum row rows?

Hold the “Ctrl + Shift” key together. First, press the left arrow to select the complete row. Then, by holding the “Ctrl + Shift” keys together, press the “down arrow” to select the whole column. Like this, we can select multiple rows in Excel without much trouble.


1 Answers

You can reverse your series before using pd.Series.rolling, and then reverse the result:

df['B'] = df['A'][::-1].rolling(10, min_periods=0).sum()[::-1]

print(df)

      A       B
0    10   550.0
1    20   650.0
2    30   750.0
3    40   850.0
4    50   950.0
5    60  1050.0
6    70  1150.0
7    80  1250.0
8    90  1350.0
9   100  1450.0
10  110  1350.0
11  120  1240.0
12  130  1120.0
13  140   990.0
14  150   850.0
15  160   700.0
16  170   540.0
17  180   370.0
18  190   190.0
like image 175
jpp Avatar answered Oct 10 '22 21:10

jpp