Pandas groupby.sum() Function

Pandas Common Functions


groupby.sum()is an aggregation function in Pandas used to sum after grouping. It is usually used withgroupby()the function, which first groups the data by the values of a column, and then sums the numeric columns in each group.

In actual data analysis,sum()it is one of the most commonly used aggregation functions. For example, calculating the total salary for each department, total sales for each region, total quantity for each category, etc.


Basic Syntax and Parameters

sum()is a member function of the GroupBy object. You need to first usegroupby()to group the data, and then call it.

Syntax Format

GroupBy.sum(numeric_only=False, min_count=-1, engine=None, engine_kwargs=None)

Parameter Description

Parameter Type Description Default Value
numeric_only bool If True, only numeric columns are summed; if False, it attempts to sum all columns. False
min_count int The minimum number of valid values required for summation. If there are fewer valid values than this number in a group, NaN is returned. -1
engine str Specify the computation engine, which can be 'cython' or 'numba'. None means Pandas automatically selects it. None
engine_kwargs dict A dictionary of additional parameters passed to the underlying engine. None

Return Value

  • Return Type:SeriesorDataFrame
  • Description: Returns the result after grouping and summation. If applied to a single column, it returns a Series; if applied to multiple columns, it returns a DataFrame.

Examples

Through a series of examples from simple to complex, let's thoroughly mastergroupby.sum()the usage.

Example 1: Basic Usage - Group by a Single Column and Sum

The most basic usage is to group by the values in one column, and then sum another column.

Example

import pandas as pd

# Create sales data DataFrame
# Simulate a table containing region, product, and sales
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 amount': [1000, 2000, 1500, 1800, 2200, 1600, 1200, 2100],
    'Quantity': [10, 20, 15, 18, 22, 16, 12, 21]
}

# Create DataFrame
df = pd.DataFrame(data)

print("Original Sales Data:")
print(df)
print()

# Group by "Region" and calculate total sales for each region
sales_by_region = df.groupby('Region')['Sales amount'].sum()

print(Total sales per region:)
print(sales_by_region)
print()

# Group by "Product" and calculate the total sales quantity for each product
quantity_by_product = df.groupby('product')['Quantity'].sum()

print(Total sales quantity for each product:)
print(quantity_by_product)

Output:

原始销售数据:
  地区  产品   销售额   数量
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

每个地区的总销售额:
地区
华东    7100
华南    3100
华北    4000
dtype: int64

每个产品的总销售数量:
产品
A    44
B    59
C    31
dtype: int64

Code Explanation:

  1. df.groupby('地区')['销售额']Indicates that the data is first grouped by the 'Region' column, and then the 'Sales amount' column is selected for operation.
  2. .sum()Sum the sales in each group.
  3. The returned result is a Series, and the index is the values of the grouping column (i.e., the names of the regions).

Example 2: Group by Multiple Columns and 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 amount': [1000, 2000, 1500, 1800, 2200, 1600, 1200, 2100],
    'Quantity': [10, 20, 15, 18, 22, 16, 12, 21]
}
df = pd.DataFrame(data)

print("Original Sales Data:")
print(df)
print()

# Group by 'Region' and 'Product' columns, calculate total sales and total quantity
# as_index=False means the grouping column is kept as a regular column in the result.
grouped = df.groupby(['Region', 'product'], as_index=False).sum()

print("Total after grouping by region and product:")
print(grouped)
print()

# Alternatively, you can sum all numeric columns without specifying columns
grouped_all = df.groupby(['Region', 'product']).sum()
print("Sum all numeric columns (returns a DataFrame):")
print(grouped_all)

Output:

原始销售数据:
  地区  产品   销售额   数量
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

按地区和产品分组后的总计:
   地区  产品   销售额   数量
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 Explanation:

  • ['Region', 'Product']Using a list allows grouping by multiple columns at the same time.
  • as_index=FalseIn this case, the result is in DataFrame format, and the grouping columns are retained as ordinary columns.
  • When no column is specified (e.g.,.sum()), the sum of all numeric columns is calculated.

Example 3: Using the min_count Parameter

min_countThis parameter controls the minimum number of valid values required for group summation. When the number of valid values in a group is less than this number, NaN is returned.

Example

import pandas as pd
import numpy as np

# Create data with 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)

print(Employee salary data (including missing values):)
print(df)
print()

# By default, sum() ignores NaN values when summing
sum_default = df.groupby('Department')['salary'].sum()
print(Default sum (ignoring NaN):)
print(sum_default)
print()

# Set min_count=3, requiring at least 3 valid values to perform summation
sum_min_count = df.groupby('Department')['salary'].sum(min_count=3)
print(Sum result when min_count=3:)
print(sum_min_count)
print()

# Set min_count=2
sum_min_count2 = df.groupby('Department')['salary'].sum(min_count=2)
print(Sum result when min_count=2:)
print(sum_min_count2)

Output:

员工工资数据(包含缺失值):
  部门     工资
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

min_count=3 时的求和结果:
部门
A    11000.0
B         NaN
C    27000.0
dtype: float64

min_count=2 时的求和结果:
部门
A    11000.0
B     7000.0
C    27000.0
dtype: float64

Code Explanation:

  • By default,sum()it ignores NaN values and only sums valid values.
  • min_count=3It means that each group must have at least 3 valid values before the sum is calculated; otherwise, NaN is returned.
  • Department A has 2 valid values (5000 and 6000), which does not meet min_count=3, so it returns NaN; Department C has 3 valid values, so it can be summed normally.

Notes:sum()By default, NaN values are ignored when summing, which is consistent with our daily understanding of "null" handling. If you need to treat NaN as 0 before summing, you can first usefillna(0)the method to fill missing values.


Pandas Common Functions

Other Extensions