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

Pandas groupby.mean() Function

Pandas groupby.mean() Function

Pandas Common Functions Common Pandas functions


groupby.mean() is an aggregation function in Pandas for computing the mean after grouping. It is used together with groupby.sum() to first group the data by the values of a column, then compute the arithmetic mean of the numeric columns in each group.

In data analysis, computing the mean is a very common need, such as the average salary per department, the average sales per region, or the average score per class.mean() The function can accomplish these tasks quickly.


Basic syntax and parameters

mean() is a member function of the GroupBy object; you must first use groupby() to group the data before calling it.

Syntax format



GroupBy.mean(numeric_only=False, engine=None, engine_kwargs=None)

Parameter Description

Parameters Type Description Default value
numeric_only bool If True, compute the mean only for numeric columns; if False, attempt to compute the mean for all columns. False
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.mean() through a series of examples from simple to complex.

Example 1: Basic Usage - Group by a Single Column to Compute the Mean

The most basic usage is to group by the values of one column and then compute the mean of another column.

Example

import

pandas

as

pd

Create a student score DataFrame

Including student name, class, and Chinese, Math, and English scores

data

=

{

   

'Name'

:

[

'Zhang San'

,

'Li Si'

,

'Wang Wu'

,

'Zhao Liu'

,

'Sun Qi'

,

'Zhou Ba'

,

'Wu Jiu'

,

'Zheng Shi'

]

,

   

'class'

:

[

'A'

,

'A'

,

'A'

,

'B'

,

'B'

,

'B'

,

'B'

,

'A'

]

,

   

'Chinese'

:

[

85

,

92

,

78

,

88

,

95

,

82

,

90

,

87

]

,

   

'Math'

:

[

90

,

85

,

92

,

78

,

88

,

91

,

85

,

89

]

,

   

'English'

:

[

88

,

90

,

85

,

92

,

87

,

89

,

91

,

86

]

}

Create DataFrame

df

=

pd.

DataFrame

(

data

)

print

(

"Student score data:"

)

print

(

df

)

print

(

)

Group by "Class" and compute the average score for each class

avg_by_class

=

df.

groupby

(

'class'

)

.

mean

(

numeric_only

=

True

)

print

(

"Average score for each class:"

)

print

(

avg_by_class

)

print

(

)

You can also compute the mean for only a single column

math_avg_by_class

=

df.

groupby

(

'class'

)

[

'Math'

]

.

mean

(

)

print

(

"Average math score for each class:"

)

print

(

math_avg_by_class

)

Expected output:

学生成绩数据:

   姓名  班级  语文  数学  英语

0  张三   A   85   90   88

1  李四   A   92   85   90

2  王五   A   78   92   85

3  赵六   B   怎么办   78   92

4  孙七   B   95   88   87

5  周八   B   82   91   89

6  吴九   B   90   85   91

7  郑十   A   87   89   86



Average score of each class:

           语文         数学         英语

班级

A     85.500000  89.000000  87.250000

B     88.750000  85.500000  89.750000



Mathematics average score for each class:

班级

A    89.0

B    85.5

dtype: float64

Code analysis:

  1. df.groupby('班级') Students are divided into groups A and B by the values of the "Class" column.
  2. .mean(numeric_only=True) Compute the mean for all numeric columns (Chinese, Math, English).
  3. In the returned result, the class is used as the index and the mean of each subject is the column data.

Example 2: Group by Multiple Columns to Compute the Mean

You can group by multiple columns at the same time and then compute the mean of 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

]

,

   

'Profit'

:

[

200

,

400

,

300

,

360

,

440

,

320

,

240

,

420

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Sales data:"

)

print

(

df

)

print

(

)

Group by "Region" and "Product" and compute the average sales and profit

avg_grouped

=

df.

groupby

(

[

'Region'

,

'Product'

]

,

as_index

=

False

)

.

mean

(

numeric_only

=

True

)

print

(

"Average sales and profit grouped by region and product:"

)

print

(

avg_grouped

)

print

(

)

Keep the MultiIndex form

avg_indexed

=

df.

groupby

(

[

'Region'

,

'Product'

]

)

.

mean

(

numeric_only

=

True

)

print

(

"Result in MultiIndex form:"

)

print

(

avg_indexed

)

Expected output:

销售数据:

  地区  产品   销售额   利润

0  华北   A   1000   200

1  华东   B   2000   reset_index

2  华南   C   1500   300

3  华北   B   1800   360

4  华东   A   保留   440

5  对齐   C   1600   320

6  华北   A   1200   240

7  华东   B   2100   420



Average sales and profit grouped by region and product:

   地区  产品    销售额     利润

0  华东   A  2200.0  440.结果

1  华东   B  2050.0  410.0

2  华南   C  1550.0  310. 产品

3  华北   A  1100.0  220.0

4  华北   B  1800.0  360.()



Multi-level index format result:

              销售额     利润

地区 产品

华东 A    2200.0  440.0

     B    2050.0  410.0

华南 C    1550.0  310.0

华北 A    1100.0  0

     B    1800()  360.0

Code analysis:

Example 3: Computing the Mean with Missing Values

When missing values (NaN) exist in the data,mean() automatically ignores these missing values in the computation.

Example

import

pandas

as

pd

import

numpy

as

np

Create employee salary data containing missing values

data

=

{

   

'Department'

:

[

'sales'

,

'sales'

,

'sales'

,

'Ji shu' (a Chinese phrase)

,

'Ji shu' (a Chinese phrase)

,

'Ji shu' (a Chinese phrase)

,

'Administration'

,

'Administration'

]

,

   

'Salary'

:

[

5000

,

6000

,

np.

nan

,

8000

,

9000

,

np.

nan

,

4500

,

np.

nan

]

}

df

=

pd.

DataFrame

(

data

)

print

(

"Employee salary data (with missing values):"

)

print

(

df

)

print

(

)

By default, mean() ignores NaN values in the computation

avg_with_nan

=

df.

groupby

(

'Department'

)

[

'Salary'

]

.

mean

(

)

print

(

"Default mean computation (ignoring NaN):"

)

print

(

avg_with_nan

)

print

(

)

If you want to include NaN values as 0 in the calculation, you need to fill them first with

avg_filled

=

df.

groupby

(

'Department'

)

[

'Salary'

]

.

apply

(

lambda

x: x.

fillna

(

0

)

.

mean

(

)

)

print

(

"Average salary after treating NaN as 0:"

)

print

(

avg_filled

)

print

(

)

Use the skipna parameter (defaults to True)

If skipna=False is set, all groups containing NaN return NaN

Note: groupby's mean has no skipna parameter, but a similar effect can be achieved with fillna

Expected output:

员工工资数据(包含缺失值):

  部门   工资

0  销售  5000.0

1  销售  6000.0

2  销售     NaN

3  技术  销售   8000.0

4  技术   9000.0

5  技术     NaN

销售  行政   4500 .0

7  行政     NaN



默认计算平均值(忽略NA N):

部门

技术    8500.0

行政    4500.0

销售    5500.0

dtype: float64



# Average salary after treating NaN as 0:

部门

技术    5666.666667

行政    2250.0

销售    3666.666667

dtype: float64

Code analysis: