Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (18.4k points)

I have the sample data frame:

       A   B   C

idx    

0      1   2   3

1      2   4   6

2      3   6   9

3      4   8   12

4      5   10  15

5      6   12  18

6      7   14  21

7      8   16  24

8      9   18  27

I am trying to sum each column 3 rows per time, with a desired outcome:

       A   B   C

   

sum1   6   12  18

sum2   15  30  45

sum3   24  48  72

Manually, I would do:

sum(df(A[0:2])

sum(df(A[3:5])

sum(df(A[6:8])

# then repeat for B and C

I was wondering if there is any more efficient way, perhaps using a for loop?

Thank you!

1 Answer

0 votes
by (36.8k points)
edited by

You can just use groupby like,

>>> df

   x   y   z

0  1   2   3

1  2   4   6

2  3   6   9

3  4   8  12

4  5  10  15

5  6  12  18

6  7  14  21

7  8  16  24

8  9  18  27

>>> df.groupby(df.index // 3).sum()

    x   y   z

0   6  12  18

1  15  30  45

2  24  48  72

>>> 

Learn Data Science with Python Course to improve your technical knowledge.

Browse Categories

...