Pandas Series.sum() function
Series.sum() is a function in Pandas used to compute the sum of all elements in a Series. It is one of the most commonly used statistical functions in data analysis and can quickly obtain the total of numerical data.
Whether computing total sales, total profit, or total quantity,sum() it helps you get it done quickly. It is especially suited to financial data, statistical reports, sales data analysis, and similar scenarios.
Basic syntax and parameters
sum() is a member function of the Series object and is called directly with the dot operator.
Syntax format
Series.sum(axis=None, skipna=True, level=None, numeric_only=None, min_count=0, **kwargs)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| axis | int | Specifies the axis; a Series has only one axis, so this parameter exists mainly for compatibility with DataFrame. | None |
| skipna | bool | If True, NaN values are skipped during the calculation; if False, encountering NaN results in NaN. | True |
| level | int or str | If the Series has a MultiIndex, specifies the level to calculate. | None |
| numeric_only | bool | If True, only numeric data is calculated; otherwise, conversion to numeric is attempted. | False |
| min_count | int | The minimum number of valid values required for the calculation. If there are fewer valid values, NaN is returned. | 0 |
Return Value
- Return Type: Numerical (
int、floatornumpy.nan) - Description: Returns the sum of all elements in the Series. If all elements are NaN (and skipna=True), 0 is returned.
Example
Let us thoroughly master Series.sum() through a series of examples from simple to complex.
Example 1: Basic Usage - Computing the Sum of a Numerical List
The most basic usage is to create a numeric Series and then call sum() Compute the total.
Example
import
pandas
as
pd
Create a Series containing sales figures
Simulate daily sales data over a week
sales_data
=
pd.
Series
(
[
1200
,
1500
,
1800
,
900
,
2100
,
1600
,
1350
]
)
Compute total sales
total_sales
=
sales_data.
sum
(
)
(
"Daily sales:"
)
(
sales_data
)
(
)
(
f
"Total sales: {total_sales}"
)
Running result:
Daily sales:
0 1200
1 1500
2 1800
3 900
4 2100
5 1600
6 1350
dtype: int64
总销售额:10450
Code analysis:
- Created a Series containing 7 days of sales figures, with integer data type.
sum()Simply iterates over all elements and adds them up to get the total 10450.
Example 2: Working with data that contains missing values
Real-world data often contains missing values,skipna The parameter determines how these missing values are handled.
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series containing missing values
Simulate missing sales data for some days
sales_with_nan
=
pd.
Series
(
[
1200
,
1500
,
np.
nan
,
1800
,
np.
nan
,
2100
,
1600
]
)
(
"Sales data with missing values:"
)
(
sales_with_nan
)
(
)
By default skipna=True, skipping NaN when computing the sum
total_skipna
=
sales_with_nan.
sum
(
)
(
f
"Sum with skipna=True (default): {total_skipna}"
)
Set skipna=False to return NaN when NaN is encountered
total_no_skipna
=
sales_with_nan.
sum
(
skipna
=
False
)
(
f
"Sum with skipna=False: {total_no_skipna}"
)
Running result:
Sales data containing missing values:
0 1200.0
1 1500.0
2 NaN
3 1800.0
4 NaN
5 2100.0
6 1600.0
dtype: float64
skipna=True(默认)时的总和:8200.0
skipna=False 时的总和:nan
Code analysis:
- When
skipna=True(the default),sum()NaN values are automatically skipped, summing only the valid values. - Calculation: 1200 + 1500 + 1800 + 2100 + 1600 = 8200
- When
skipna=False, as long as any NaN is present, the result is NaN, which is useful when you need to be clearly aware of data completeness.
Example 3: Using the min_count Parameter
min_count The parameter can set the minimum number of valid values required for the calculation, which is useful when data sufficiency must be guaranteed.
Example
import
pandas
as
pd
import
numpy
as
np
Create a Series that is mostly missing values
sparse_data
=
pd.
Series
(
[
np.
nan
,
np.
nan
,
100
,
np.
nan
,
np.
nan
]
)
(
"Mostly missing data:"
)
(
sparse_data
)
(
)
Default min_count=0; computes as long as there are at least 0 valid values
result_default
=
sparse_data.
sum
(
)
(
f
"Result with min_count=0 (default): {result_default}"
)
Set min_count=3; requires at least 3 valid values to compute
result_min_count
=
sparse_data.
sum
(
min_count
=
3
)
(
f
"Result with min_count=3: {result_min_count}"
)
Set min_count=2; only 2 valid values are needed
result_min_count_2
=
sparse_data.
sum
(
min_count
=
2
)
(
f
"Result with min_count=2: {result_min_count_2}"
)
Running result:
Most missing data:
0 NaN
1 NaN
2 100.0
3 NaN
4 NaN
dtype: float64
min_count=0(默认)时的结果:100.0
min_count=3 时的结果:nan
min_count=2 时的结果:100.0
Code analysis:
- This Series has only 1 valid value (100).
min_count=3Means at least 3 valid values are required to compute, but there is only 1, so NaN is returned.min_count=2Means at least 2 valid values are required; there is only 1 valid value, so the condition is not met and NaN is returned.- This parameter is very useful in analysis scenarios with high data quality requirements, helping identify insufficient valid data.
Example 4: Application in Real Data Analysis
Combining real business scenarios, this demonstrates sum() a typical application of the function.
Example
import
pandas
as
pd
Create a mock sales data DataFrame
sales_data
=
pd.
DataFrame
(
{
'Month'
:
[
'Jan'
,
'Feb'
,
'Mar'
,
'Apr'
,
'May'
,
'Jun'
]
,
'East China region'
:
[
12000
,
15000
,
18000
,
16000
,
14000
,
17000
]
,
'North China region'
:
[
10000
,
11000
,
13000
,
12500
,
11500
,
14000
]
,
'South China region'
:
[
15000
,
17000
,
19000
,
18000
,
16000
,
20000
]
}
)
(
"First-half sales data by region:"
)
(
sales_data
)
(
)
Compute the half-year total sales for each region
for
region
in
[
'East China region'
,
'North China region'
,
'South China region'
]
:
total
=
sales_data
[
region
]
.
sum
(
)
(
f
"{region} half-year total sales: {total} yuan"
)
(
)
Compute the total sales across all regions
total_all
=
sales_data
[
[
'East China region'
,
'North China region'
,
'South China region'
]
]
.
sum
(
)
.
sum
(
)
(
f
"Total half-year sales for all regions: {total_all} yuan"
)
Running result:
Sales data for each region in the first half of the year:
月份 华东区 华北区 华南区
0 1月 12000 10000 15000
1 2月 15000 11000 17000
2 3月 18000 13000 19000
3 4月 16000 12500 18000
4 5月 14000 11500 16000
5 6月 17000 14000 20000
华东区半年总销售额:92000 元
华北区半年总销售额:72000 元
华南区半年总销售额:105000 元
所有区域半年总销售额:269000 元
Notes
sum()NaN values are skipped by default, which is the desired behavior in most cases.- To sum a Series containing non-numeric data, you need to clean the data first or use
numeric_only=Trueparameter was added. min_countThe parameter is very useful in data validation and quality checks, helping identify insufficient valid data.- For large datasets,
sum()It generally performs well because it uses NumPy's vectorized operations under the hood.
Summary
Series.sum() is one of the most fundamental and commonly used statistical functions in Pandas. Its main features include:
- Simple and easy to use, called directly through the dot operator.
- Supports handling missing values, controlled by the
skipnaparameter. - can be used via
min_countThe parameter sets the minimum requirement for valid values. - Uses NumPy's optimized implementation under the hood for high computational efficiency.
In real data analysis,sum() It is often used together with other aggregation functions (such as mean()、count() , etc.) for comprehensive statistical data analysis.
Common Pandas functions