Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas groupby.sum() Function

Pandas groupby.sum() Function

Pandas Common Functions Common Pandas functions


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


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

)

print

(

"Original sales data:"

)

print

(

df

)

print

(

)

Group by "Region" and compute the total sales for each region

sales_by_region

=

df.

groupby

(

'Region'

)

[

'Sales'

]

.

sum

(

)

print

(

"Total sales for each region:"

)

print

(

sales_by_region

)

print

(

)

Group by "Product" and compute 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

)

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:

  1. df.groupby('地区')['销售额'] means first group by the "Region" column, then select the "Sales" column for the operation.
  2. .sum() Sum the sales in each group.
  3. 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

)

print

(

"Original sales data:"

)

print

(

df

)

print

(

)

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

(

)

print

(

"Totals grouped by region and product:"

)

print

(

grouped

)

print

(

)

You can also omit the column specification and sum all numeric columns

grouped_all

=

df.

groupby

(

[

'Region'

,

'Product'

]

)

.

sum

(

)

print

(

"Sum of all numeric columns (returning a DataFrame):"

)

print

(

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:

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

)

print

(

"Employee salary data (with 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 to require at least 3 valid values before summing

sum_min_count

=

df.

groupby

(

'Department'

)

[

'Salary'

]

.

sum

(

min_count

=

3

)

print

(

"Sum result with 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 with min_count=2:"

)

print

(

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:


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 use fillna(0) to fill missing values.


Pandas Common Functions Common Pandas functions