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

Pandas Series.median() Function

Pandas Series.median() Function

Pandas Common Functions Common Pandas functions


Series.median() is a Pandas function used to calculate the median (middle value) of a Series. The median is the value at the middle position after sorting the data; it is unaffected by extreme values and is a robust measure of central tendency.

When data contains outliers or follows a skewed distribution, the median reflects the center of the data more accurately than the mean. It is often used in income data analysis, housing price statistics, score analysis, and similar scenarios.


Basic syntax and parameters

median() is a member function of the Series object and is called directly with the dot operator.

Syntax format



Series.median(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.median() through a series of examples from simple to complex.

Example 1: Basic Usage - Median of an Odd Number of Elements

For data with an odd number of elements, the median is the value in the middle after sorting.

Example

import

pandas

as

pd

Create a Series containing employee incomes

Simulate the monthly incomes of 7 employees in a department (unit: thousand yuan)

income

=

pd.

Series

(

[

5

,

6

,

7

,

8

,

9

,

10

,

50

]

)

Calculate the median

median_income

=

income.

median

(

)

print

(

"Employee Monthly Incomes (Thousand Yuan):"

)

print

(

income

)

print

(

)

print

(

f

"Average Income: {income.mean():.2f} Thousand Yuan"

)

print

(

f

"Median Income: {median_income} Thousand Yuan"

)

print

(

)

print

(

"Note: the mean is greatly affected by the extreme value (50 thousand yuan), while the median better reflects the true level."

)

Running result:



员工月收入(千元):

0     5

1     6

2     7

3     8

4     9

5    10

6    50

dtype: int64



平均收入:13.57 千元

中位数收入:8.0 千元

Code analysis:

Example 2: Median of an Even Number of Elements

For data with an even number of elements, the median is the average of the two middle elements.

Example

import

pandas

as

pd

Create a Series with 6 elements

Simulate the exam scores of 6 students

scores

=

pd.

Series

(

[

75

,

82

,

88

,

92

,

95

,

100

]

)

Calculate the median

median_score

=

scores.

median

(

)

print

(

"Student exam scores:"

)

print

(

scores

)

print

(

)

print

(

f

"Average Score: {scores.mean():.2f}"

)

print

(

f

"Median Score: {median_score}"

)

Running result:



Student exam scores:

0    75

1    82

2    88

3    92

4    95

5   100

dtype: int64



平均成绩:88.67

中位数成绩:90.0

Code analysis:

Example 3: Handling Data with Missing Values

skipna parameter determines how missing values are handled.

Example

import

pandas

as

pd

import

numpy

as

np

Create a Series containing missing values

data_with_nan

=

pd.

Series

(

[

10

,

20

,

np.

nan

,

30

,

40

,

np.

nan

,

50

]

)

print

(

"Data containing missing values:"

)

print

(

data_with_nan

)

print

(

)

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

median_skipna

=

data_with_nan.

median

(

)

print

(

f

"Median with skipna=True (default): {median_skipna}"

)

Set skipna=False

median_no_skipna

=

data_with_nan.

median

(

skipna

=

False

)

print

(

f

"Median with skipna=False: {median_no_skipna}"

)

Running result:



Data containing missing values:

0    10.0

1    20.0

2       NaN

3    30.0

4    40.0

5       NaN

6    50.0

dtype: float64



skipna=True(默认)时的中位数:30.0

skipna=False 时的中位数:nan

Code analysis:

Example 4: Comparing Application Scenarios of the Mean and the Median

Demonstrate the advantages of the median when handling skewed data.

Example

import

pandas

as

pd

Simulate the monthly income data of 10 households in a neighborhood

Most people earn between 3000 and 5000 yuan, but there are a few high earners

income_data

=

pd.

Series

(

[

3000

,

3500

,

3800

,

4000

,

4200

,

4500

,

4800

,

5000

,

8000

,

50000

]

)

print

(

"Monthly Income Data of Neighborhood Residents (Yuan):"

)

print

(

income_data

)

print

(

)

mean_income

=

income_data.

mean

(

)

median_income

=

income_data.

median

(

)

print

(

f

"Mean: {mean_income:.2f} Yuan"

)

print

(

f

"Median: {median_income} Yuan"

)

print

(

)

print

(

"Analysis:"

)

print

(

"The mean (10380 yuan) is pulled greatly upward by the extreme value (50000 yuan)."

)

print

(

"The median (4350 yuan) better reflects the true income level of most residents."

)

print

(

"This is why statistical agencies more often use the median when publishing income data."

)

Running result:



小区住户月收入数据(元):

0     3000

1     3500

2     3800

3     4000

4     4200

5     4500

6     4800

7     5000

8     8000

9    50000

dtype: int64



平均值:10380.00 元

中位数:4350.0 元


Notes


Summary

Series.median() It is an important function for describing central tendency. Its main features include:

In real data analysis, it is recommended to calculate both the mean and the median to gain a more complete understanding of the data distribution. When the two differ greatly, it suggests the data may have a skewed distribution or outliers.

Pandas Common Functions Common Pandas functions