Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append column total to pandas dataframe every 4th row?

I have the following dataframe with weekly numbers for column A, B and C:

week  A B C
0     1 0 0
1     1 0 1
2     0 1 0
3     1 1 1
4     1 0 0
5     0 0 1
6     0 1 0
7     1 1 1
8     1 0 0
9     0 0 1
10    0 1 0
11    1 1 1

and I want to append the dataframe with a row consisting of the monthly total for each column (so the previous 4 weeks together), with a wanted outcome something like this:

week   A B C
0      1 0 0
1      1 0 1
2      0 1 0
3      1 1 1
total  3 2 2
4      1 0 0
5      0 0 1
6      1 1 0
7      2 1 0
total  4 2 1
8      1 0 0
9      0 0 1
10     0 0 0
11     1 0 1
total  2 0 2

I have used

df.groupby(df.index // 4).sum(numeric_only=True, axis=0)

to get the monthly numbers but I do not know how to get it appended in the df. Any ideas? Thanks

like image 817
mrcw Avatar asked Sep 05 '25 03:09

mrcw


1 Answers

pd.concat

Iterating through the groupby object allows us to append the total row to each sub-dataframe. By passing this through a dictionary comprehension/pd.concat we conveniently get month added as a level in the index to disambiguate the 'total' identifier in the index.

pd.concat({
    m: d.append(d.sum().rename('total'))
    for m, d in df.groupby(df.index // 4)
}, names=['month'])

             A  B  C
month week          
0     0      1  0  0
      1      1  0  1
      2      0  1  0
      3      1  1  1
      total  3  2  2
1     4      1  0  0
      5      0  0  1
      6      0  1  0
      7      1  1  1
      total  2  2  2
2     8      1  0  0
      9      0  0  1
      10     0  1  0
      11     1  1  1
      total  2  2  2
like image 177
piRSquared Avatar answered Sep 07 '25 21:09

piRSquared