Pandas DataFrame sum() Method

Pandas DataFrame sum() method calculates the sum of the elements in each column (by default) or along the rows. You can specify the axis along which you want to compute the sum.


dataframe.sum(axis=None, skipna=True, level=None, 
              numeric_only=None, min_count=0, **kwargs)


axis: {0 or ‘index’, 1 or ‘columns’}, default 0. Axis along which the sum is computed. If set to 0 or ‘index’, it computes the sum along the columns (default). If set to 1 or ‘columns’, it computes the sum along the rows.

skipna: bool, default True. Exclude NA/null values when calculating the sum. If set to False, NA values will be treated as zero.

level: int or level name, optional. For DataFrames with multi-level index, you can specify the level to compute the sum.

numeric_only: bool, optional. Include only float, int, and boolean columns. If None (default), attempt to sum over all columns of the DataFrame.

min_count: int, default 0. The required number of valid values to operate. If fewer than min_count non-NA values are present, the result will be NA.


import pandas as pd

data = {
  "A": [11, 21, 31],
  "B": [41, 51, 61],
  "C": [71, 81, 91]

df = pd.DataFrame(data)

column_sum = df.sum()
print("Sum along columns:")

row_sum = df.sum(axis=1)
print("\nSum along rows:")


Sum along columns:
A   63
B   153
C   243
dtype: int64

Sum along rows:
0   123
1   153
2   183
dtype: int64

In this code, we created a sample DataFrame df and used the sum() method to calculate the sum along the columns (default) and the rows (by setting axis=1).

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.