8

I have a df as such:

         column A    column B    column C  .... ColumnZ 
 index
   X        1           4           7              10
   Y        2           5           8              11
   Z        3           6           9              12

For the life on me I can't figure out how to sum rows for each column, to arrive at a summation df:

         column A    column B    column C  .... ColumnZ 
 index
 total       6           16          25             33

Any thoughts?

3
  • 3
    df.sum().to_frame().T.rename_axis('Total') ... ? Commented Jul 24, 2020 at 18:26
  • How can that be a duplicate of a question asking "I would like to add a column 'e' which is the sum of columns 'a', 'b' and 'd'"? Commented Jun 21, 2024 at 19:06
  • "on me I can't figure out how to sum rows for each column, to arrive at a summation [...]", you can't have 4+5+6 = 16, I confirm :-) Commented Jun 21, 2024 at 19:09

2 Answers 2

11

You can use:

df.loc['total'] = df.sum(numeric_only=True, axis=0)
Sign up to request clarification or add additional context in comments.

1 Comment

I would just like to add: df.sum(numeric_only=True, axis=1) to sum the columns instead of rows. Thanks!
7

Try this:

import pandas as pd

df = pd.DataFrame({'column A': [1, 2, 3], 'column B': [4, 5, 6], 'column C': [7, 8, 9]})

df.loc['total'] = df.sum()

print(df)

Output:

       column A  column B  column C
0             1         4         7
1             2         5         8
2             3         6         9
total         6        15        24

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.