Pandas How To Uncategorized How to calculate sum of rows and columns in Pandas

How to calculate sum of rows and columns in Pandas

Here’s how to calculate sum of rows and columns in Pandas dataframe.

In this post, I will show you how to easily prepare a summary of columns and rows in a dataframe.

How to calculate sum of rows

You can simply use the sum function to calculate the sum of the rows. As a parameter, add only axis=1 to indicate that you want to sum the rows.

import pandas as pd

my_df = pd.DataFrame({'Exam1': [2, 5, 7, 46],
                      'Exam2': [12, 21, 5, 22],
                      'Exam3': [8, 22, 9, 12]})


my_df['Sum_of_Rows'] = my_df.sum(axis=1)
print(f'Sum of rows: \n {my_df}')

The summary is displayed in a separate column that I created.

how to calculate sum of rows

How to calculate sum of columns

Also use the sum function to calculate the sum of the columns. As a parameter, add axis=0, which indicates that Pandas is supposed to sum the columns.

import pandas as pd

my_df = pd.DataFrame({'Exam1': [2, 5, 7, 46],
                      'Exam2': [12, 21, 5, 22],
                      'Exam3': [8, 22, 9, 12]})


sum_of_columns = my_df.sum(axis=0)
print(f'Sum of columns: \n{sum_of_columns}')

Pandas displays a summary of the columns along with the data type they contain.

how to calculate sum of columns

How to calculate cumsum of column

It is also possible to calculate a cumulative sum for a column in the dataframe. To do this, create a new column and indicate for which column you want to calculate the cumulative total.

import pandas as pd

my_df = pd.DataFrame({'Column1': [2, 5, 7, 46],
                      'Column2': [12, 21, 5, 22],
                      'Column3': [8, 22, 9, 12]})


my_df['Cumsum_of_Column1'] = my_df['Column1'].cumsum()
print(f'Cumsum of Column1: \n {my_df}')

how to calculate cumsum of column

See also:
How to calculate cumulative sum in Pandas
How to count specific value in column
How to add a column

Tags: ,

2 thoughts on “How to calculate sum of rows and columns in Pandas”

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post