Pandas groupby.sum() Function
groupby.sum() is an aggregation function in Pandas for computing sums after grouping. It is usually used together with groupby() to first group the data by the values of a column, then sum the numeric columns in each group.
In real data analysis,sum() is one of the most commonly used aggregation functions, such as computing the total salary per department, the total sales per region, or the total quantity per category.
Basic syntax and parameters
sum() is a member function of the GroupBy object; you must first use groupby() to group the data before calling it.
Syntax format
GroupBy.sum(numeric_only=False, min_count=-1, engine=None, engine_kwargs=None)
Parameter Description
| Parameters | Type | Description | Default value |
|---|---|---|---|
| numeric_only | bool | If True, sum only numeric columns; if False, attempt to sum all columns. | False |
| min_count | int | The minimum number of valid values required to perform the sum. If a group has fewer valid values than this, NaN is returned. | -1 |
| engine | str | Specify the computation engine, which can be 'cython' or 'numba'. None means Pandas chooses automatically. | None |
| engine_kwargs | dict | A dictionary of extra arguments passed to the underlying engine. | None |
Return Value
- Return Type:
SeriesorDataFrame - Description: Returns the result of grouped summation. If used on a single column, returns a Series; if used on multiple columns, returns a DataFrame.
Example
Let us thoroughly master groupby.sum() through a series of examples from simple to complex.
Example 1: Basic Usage - Group by a Single Column to Sum
The most basic usage is to group by the values of one column and then sum another column.
Example
import
pandas
as
pd
Create a sales data DataFrame
Simulate a table containing region, product, and sales amount
data
=
{
'Region'
:
[
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
]
,
'Product'
:
[
'A'
,
'B'
,
'C'
,
'B'
,
'A'
,
'C'
,
'A'
,
'B'
]
,
'Sales'
:
[
1000
,
2000
,
1500
,
1800
,
2200
,
1600
,
1200
,
2100
]
,
'quantity'
:
[
10
,
20
,
15
,
18
,
22
,
16
,
12
,
21
]
}
Create DataFrame
df
=
pd.
DataFrame
(
data
)
(
"Original sales data:"
)
(
df
)
(
)
Group by "Region" and compute the total sales for each region
sales_by_region
=
df.
groupby
(
'Region'
)
[
'Sales'
]
.
sum
(
)
(
"Total sales for each region:"
)
(
sales_by_region
)
(
)
Group by "Product" and compute the total sales quantity for each product
quantity_by_product
=
df.
groupby
(
'Product'
)
[
'quantity'
]
.
sum
(
)
(
"Total sales quantity for each product:"
)
(
quantity_by_product
)
Running result:
Original sales data:
地区 产品 销售额 数量
0 华北 A 1000 10
1 华东 B 2000 20
2 华南 C 1500 15
3 华北 B 1800 18
4 华东 A 2200 22
5 华南 C 1600 16
6 华北 A 1200 12
7 华东 B 2100 21
Total sales amount for each region:
地区
华东 7100
华南 3100
华北 4000
dtype: int64
Total sales quantity for each product:
产品
A 44
B 59
C 31
dtype: int64
Code analysis:
df.groupby('地区')['销售额']means first group by the "Region" column, then select the "Sales" column for the operation..sum()Sum the sales in each group.- The returned result is a Series whose index is the grouping column values (i.e., the region names).
Example 2: Group by Multiple Columns to Sum
You can group by multiple columns at the same time and then sum the numeric columns.
Example
import
pandas
as
pd
Create sales data
data
=
{
'Region'
:
[
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
,
'South China'
,
'North China'
,
'East China'
]
,
'Product'
:
[
'A'
,
'B'
,
'C'
,
'B'
,
'A'
,
'C'
,
'A'
,
'B'
]
,
'Sales'
:
[
1000
,
2000
,
1500
,
1800
,
2200
,
1600
,
1200
,
2100
]
,
'quantity'
:
[
10
,
20
,
15
,
18
,
22
,
16
,
12
,
21
]
}
df
=
pd.
DataFrame
(
data
)
(
"Original sales data:"
)
(
df
)
(
)
Group by both "Region" and "Product" columns and compute the total sales and total quantity
as_index=False means the grouping columns are kept as normal columns in the result
grouped
=
df.
groupby
(
[
'Region'
,
'Product'
]
,
as_index
=
False
)
.
sum
(
)
(
"Totals grouped by region and product:"
)
(
grouped
)
(
)
You can also omit the column specification and sum all numeric columns
grouped_all
=
df.
groupby
(
[
'Region'
,
'Product'
]
)
.
sum
(
)
(
"Sum of all numeric columns (returning a DataFrame):"
)
(
grouped_all
)
Running result:
Original sales data:
地区 产品 销售额 数量
0 华北 A 1000 10
1 华东 B 2000 20
2 华南 C 1500 15
3 华北 B 1800 18
4 华东 A 2200 22
5 华南 C 1600 16
6 华北 A 1200 12
7 华东 B 2100 21
Total grouped by region and product:
地区 产品 销售额 数量
0 华东 A 2200 22
1 华东 B 4100 41
2 华南 C 3100 31
3 华北 A 2200 22
4 华北 B 1800 18
对所有数值列求和(返回DataFrame):
销售额 数量
地区 产品
华东 A 2200 22
B 4100 41
华南 C 3100 31
华北 A 2200 22
B 1800 18
Code analysis:
['地区', '产品']Using a list allows you to group by multiple columns at once.as_index=False, the result is in DataFrame format, with the grouping columns kept as normal columns.- When no column is specified (such as
.sum()), all numeric columns are summed.
Example 3: Using the min_count Parameter
min_count parameter controls the minimum number of valid values required for grouped summation. When a group has fewer valid values, NaN is returned.
Example
import
pandas
as
pd
import
numpy
as
np
Create data containing missing values
data
=
{
'Department'
:
[
'A'
,
'A'
,
'A'
,
'B'
,
'B'
,
'B'
,
'C'
,
'C'
,
'C'
]
,
'Salary'
:
[
5000
,
6000
,
np.
nan
,
7000
,
np.
nan
,
np.
nan
,
8000
,
9000
,
10000
]
}
df
=
pd.
DataFrame
(
data
)
(
"Employee salary data (with missing values):"
)
(
df
)
(
)
By default, sum() ignores NaN values when summing
sum_default
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
sum
(
)
(
"Default sum (ignoring NaN):"
)
(
sum_default
)
(
)
Set min_count=3 to require at least 3 valid values before summing
sum_min_count
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
sum
(
min_count
=
3
)
(
"Sum result with min_count=3:"
)
(
sum_min_count
)
(
)
Set min_count=2
sum_min_count2
=
df.
groupby
(
'Department'
)
[
'Salary'
]
.
sum
(
min_count
=
2
)
(
"Sum result with min_count=2:"
)
(
sum_min_count2
)
Running result:
员工工资数据(包含缺失值):
部门 工资
0 A 5000.0
1 A 6000.0
2 A NaN
3 B 7000.0
4 B NaN
5 B NaN
6 C 8000.0
7 C 9000.0
8 C 10000.0
默认求和(忽略NaN):
部门
A 11000.0
B 7000.0
C 27000.0
dtype: float64
Summation result when min_count=3:
部门
A 11000.0
B NaN
C 27000.0
dtype: float64
Sum result when min_count=2:
部门
A 11000.0
B 7000.0
C 27000.0
dtype: float64
Code analysis:
- By default,
sum()ignores NaN values and sums only the valid values. min_count=3means each group must have at least 3 valid values to be summed; otherwise NaN is returned.- Department A has 2 valid values (5000 and 6000), which does not satisfy min_count=3, so NaN is returned; Department C has 3 valid values and can be summed normally.
Notes:
sum()By default, NaN values are ignored when summing, which is consistent with our everyday understanding of "null value" handling. If you need to treat NaN as 0 before summing, you can first usefillna(0)to fill missing values.
Common Pandas functions