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.
Syntax
dataframe.sum(axis=None, skipna=True, level=None,
numeric_only=None, min_count=0, **kwargs)
Parameters
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.
Example
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:")
print(column_sum)
row_sum = df.sum(axis=1)
print("\nSum along rows:")
print(row_sum)
Output
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).