Pandas Series.mean() Function
Series.mean() is a Pandas function used to calculate the mean of all elements in a Series. The mean is one of the most commonly used statistical measures, representing the central tendency of a dataset.
Whether calculating average salary, average sales, or average scores,mean() it can help you do so quickly. It is a core measure of the central tendency of a dataset.
Basic syntax and parameters
mean() is a member function of the Series object and is called directly with the dot operator.
Syntax format
Series.mean(axis=None, skipna=True, level=None, numeric_only=None, **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 |
Return Value
- Return Type:
float(Even if the input consists of integers, the return value is converted to a floating-point number.) - Description: Returns the mean of all valid elements in the Series. If all elements are NaN, NaN is returned.
Example
Let us thoroughly master Series.mean() through a series of examples from simple to complex.
Example 1: Basic Usage - Calculating the Average of Student Scores
The most basic usage is to create a numeric Series and then call mean() to calculate the mean.
Example
import
pandas
as
pd
Create a Series containing student scores
Simulate the exam scores of 8 students in a class
scores
=
pd.
Series
(
[
85
,
92
,
78
,
90
,
88
,
76
,
95
,
82
]
)
Calculate the average score
average_score
=
scores.
mean
(
)
(
"Student exam scores:"
)
(
scores
)
(
)
(
f
"Average score: {average_score:.2f} points"
)
Running result:
Student exam scores:
0 85
1 92
2 78
3 90
4 88
5 76
6 95
7 82
dtype: int64
平均成绩:85.75 分
Code analysis:
- A Series containing the scores of 8 students was created.
mean()The sum of all scores (685) divided by the number of students (8) gives the mean of 85.75.- Note: the return value is a float, even if the input consists of integers.
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 a student who missed some exams due to illness
scores_with_nan
=
pd.
Series
(
[
85
,
92
,
np.
nan
,
90
,
88
,
np.
nan
,
95
,
82
]
)
(
"Data containing missed exam scores:"
)
(
scores_with_nan
)
(
)
By default, skipna=True, which skips NaN values when calculating the mean
average_skipna
=
scores_with_nan.
mean
(
)
(
f
"Average score with skipna=True (default): {average_skipna:.2f}"
)
Set skipna=False to return NaN when NaN is encountered
average_no_skipna
=
scores_with_nan.
mean
(
skipna
=
False
)
(
f
"Average score with skipna=False: {average_no_skipna}"
)
Running result:
Data containing absent grades:
0 85.0
1 92.0
2 NaN
3 90.0
4 88.0
5 NaN
6 95.0
7 82.0
dtype: float64
skipna=True(默认)时的平均成绩:88.67
skipna=False 时的平均成绩:nan
Code analysis:
- When
skipna=TrueWith the default value, only valid values are averaged. - Calculation: (85 + 92 + 90 + 88 + 95 + 82) / 6 = 532 / 6 = 88.67
- When
skipna=FalseWhen skipna=False, the result is NaN whenever any NaN is present.
Example 3: Using a MultiIndex Series
For a Series with a hierarchical index (MultiIndex), you can specify which level to average.
Example
import
pandas
as
pd
Create a MultiIndex Series
Simulate the scores of students in two classes
multi_index_scores
=
pd.
Series
(
[
85
,
92
,
78
,
90
,
88
,
76
,
95
,
82
]
,
index
=
pd.
MultiIndex
.
from_tuples
(
[
(
'Class A'
,
'Student 1'
)
,
(
'Class A'
,
'Student 2'
)
,
(
'Class A'
,
'Student 3'
)
,
(
'Class A'
,
'Student 4'
)
,
(
'Class B'
,
'Student 1'
)
,
(
'Class B'
,
'Student 2'
)
,
(
'Class B'
,
'Student 3'
)
,
(
'Class B'
,
'Student 4'
)
]
,
names
=
[
'class'
,
'Student'
]
)
)
(
"Student Scores of the Two Classes:"
)
(
multi_index_scores
)
(
)
Calculate the average score of all students
overall_mean
=
multi_index_scores.
mean
(
)
(
f
"Average Score of All Students: {overall_mean:.2f}"
)
(
)
Calculate the average score by class (using the level parameter)
class_a_mean
=
multi_index_scores.
xs
(
'Class A'
,
level
=
'class'
)
.
mean
(
)
class_b_mean
=
multi_index_scores.
xs
(
'Class B'
,
level
=
'class'
)
.
mean
(
)
(
f
"Average Score of Class A Students: {class_a_mean:.2f}"
)
(
f
"Average Score of Class B Students: {class_b_mean:.2f}"
)
Running result:
Student scores of two classes:
班级 学生
A班 学生1 85
学生2 92
学生3 78
学生4 90
B班 学生1 88
学生2 76
学生3 95
学生4 82
dtype: int64
所有学生平均成绩:85.75
A班学生平均成绩:86.25
B班学生平均成绩:85.25
Code analysis:
- A Series with two index levels was created, with index names "class" and "student".
- Directly calling
mean()It calculates the average of all elements. - Use
xs()The method can filter data by a certain level before calculating the mean.
Example 4: Application in Real Data Analysis
Combining real business scenarios, this demonstrates mean() a typical application of the function.
Example
import
pandas
as
pd
import
numpy
as
np
Create simulated daily stock closing price data
stock_prices
=
pd.
Series
(
[
100.5
,
102.3
,
98.7
,
101.2
,
103.5
,
105.2
,
103.8
,
107.1
,
108.3
,
106.9
]
,
index
=
[
'Monday'
,
'Tuesday'
,
'Wednesday'
,
'Thursday'
,
'Friday'
,
'Monday'
,
'Tuesday'
,
'Wednesday'
,
'Thursday'
,
'Friday'
]
)
Create data for two periods
week1
=
stock_prices
[
:
5
]
week2
=
stock_prices
[
5
:
]
(
"Stock Prices for Week 1:"
)
(
week1
)
(
f
"Average Price for Week 1: {week1.mean():.2f}"
)
(
)
(
"Stock Prices for Week 2:"
)
(
week2
)
(
f
"Average Price for Week 2: {week2.mean():.2f}"
)
(
)
Calculate the difference between the average prices of the two weeks
price_diff
=
week2.
mean
(
)
- week1.
mean
(
)
(
f
"Difference in Average Price Between the Two Weeks: {price_diff:.2f}"
)
Running result:
First week stock prices:
周一 100.5
周二 102.3
周三 98.7
周四 101.2
周五 103.5
dtype: float64
第一周平均价格:101.24
Second week stock prices:
周一 105.2
周二 103.8
周三 107.1
周四 108.3
周五 106.9
dtype: float64
第二周平均价格:106.26
两周平均价格差异:5.02
Notes
mean()The return value is always a float, even if all input data are integers.- The mean is sensitive to extreme values (outliers), which can significantly affect the result.
- If the data contains many missing values,
skipna=Truebe aware that the mean is calculated from only part of the data. - For a Series containing non-numeric data, you need to clean the data first or use
numeric_only=Trueparameter was added.
Summary
Series.mean() is one of the most 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. - Supports MultiIndex, allowing calculation by selected level.
- The return value is always a float, ensuring precision.
The mean is an important measure of central tendency, but when extreme values are present, you may want to consider using the median (median()) to better reflect the center of the data.
Common Pandas functions