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

Pandas Series.mean() Function

Pandas Series.mean() Function

Pandas Common Functions Common Pandas functions


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


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

(

)

print

(

"Student exam scores:"

)

print

(

scores

)

print

(

)

print

(

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:

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

]

)

print

(

"Data containing missed exam scores:"

)

print

(

scores_with_nan

)

print

(

)

By default, skipna=True, which skips NaN values when calculating the mean

average_skipna

=

scores_with_nan.

mean

(

)

print

(

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

)

print

(

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:

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'

]

   

)

)

print

(

"Student Scores of the Two Classes:"

)

print

(

multi_index_scores

)

print

(

)

Calculate the average score of all students

overall_mean

=

multi_index_scores.

mean

(

)

print

(

f

"Average Score of All Students: {overall_mean:.2f}"

)

print

(

)

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

(

)

print

(

f

"Average Score of Class A Students: {class_a_mean:.2f}"

)

print

(

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:

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

:

]

print

(

"Stock Prices for Week 1:"

)

print

(

week1

)

print

(

f

"Average Price for Week 1: {week1.mean():.2f}"

)

print

(

)

print

(

"Stock Prices for Week 2:"

)

print

(

week2

)

print

(

f

"Average Price for Week 2: {week2.mean():.2f}"

)

print

(

)

Calculate the difference between the average prices of the two weeks

price_diff

=

week2.

mean

(

)

mean

(

)

print

(

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


Summary

Series.mean() is one of the most commonly used statistical functions in Pandas. Its main features include:

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.

Pandas Common Functions Common Pandas functions