The Wayback Machine - https://web.archive.org/web/20250311085937/https://www.geeksforgeeks.org/python-pandas-dataframe-sum/
Open In App

Pandas dataframe.sum()

Last Updated : 06 Dec, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

DataFrame.sum() function allows users to compute the sum of values along the specified axis. It can be used to sum values along either the index (rows) or columns, while also allowing flexibility with how missing (NaN) values are handled.

Syntax: DataFrame.sum(axis=None, skipna=None, level=None, numeric_only=None, min_count=0, **kwargs)

Parameters:

  • axis : {index (0), columns (1)}
  • skipna : Exclude NA/null values when computing the result.
  • level : If the axis is a MultiIndex (hierarchical), count along a particular level, collapsing into a Series
  • numeric_only : Include only float, int, boolean columns. If None, will attempt to use everything, then use only numeric data. Not implemented for Series.
  • min_count : The required number of valid values to perform the operation. If fewer than min_count non-NA values are present the result will be NA.

Returns: A Series or scalar with the summed values along the specified axis (columns or rows).

Examples of Using DataFrame.sum()

1. Summing Values Across Columns (default behavior)

Let’s use the Pandas sum() function to find the sum of all values over the index axis (rows) in a DataFrame. In this example, we’ll exclude NaN values while calculating the sum.

Dataset Link: nba.csv

Python
import pandas as pd
df = pd.read_csv("nba.csv")
print(df.dtypes)

# Convert columns to numeric (if applicable)
df = df.apply(pd.to_numeric, errors='coerce')

# Sum the numeric columns along the index (rows), skipping NaN values
df_sum = df.sum(axis=0, skipna=True)
print("\n Finding Sum over Index Axis")
print(df_sum)

Output:

Summing-values-across-columns

Example 2: Sum Over the Column Axis

Now, let’s calculate the sum of all values over the column axis (columns) using the sum() function. Again, we’ll ensure that NaN values are excluded from the sum.

Python
import pandas as pd
df = pd.read_csv("nba.csv")
print(df.dtypes)

# Select only numeric columns for summing
df_numeric = df.select_dtypes(include=['number'])

# Sum over the column axis (axis=1) and skip NaN values
df_sum_column = df_numeric.sum(axis=1, skipna=True)
print("\n Finding Sum over Column Axis")
print(df_sum_column)

Output:

Summing-over-the-column-axis




Next Article

Similar Reads

three90RightbarBannerImg