Pandas Series.median() Function
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
- Return Type:
float - Description: Returns the median of all elements in the Series. If the number of elements is even, the average of the two middle elements is returned.
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
(
)
(
"Employee Monthly Incomes (Thousand Yuan):"
)
(
income
)
(
)
(
f
"Average Income: {income.mean():.2f} Thousand Yuan"
)
(
f
"Median Income: {median_income} Thousand Yuan"
)
(
)
(
"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:
- Sorted data: [5, 6, 7, 8, 9, 10, 50]
- The middle position is the 4th element (index 3), with a value of 8.
- Due to an extreme value (50), the mean (13.57) is pulled upward, while the median (8) better reflects the income level of most people.
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
(
)
(
"Student exam scores:"
)
(
scores
)
(
)
(
f
"Average Score: {scores.mean():.2f}"
)
(
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:
- Sorted data: [75, 82, 88, 92, 95, 100]
- The two middle elements are 88 and 92 (indices 2 and 3).
- Median = (88 + 92) / 2 = 90.
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
]
)
(
"Data containing missing values:"
)
(
data_with_nan
)
(
)
By default, skipna=True, which skips NaN values when calculating the median
median_skipna
=
data_with_nan.
median
(
)
(
f
"Median with skipna=True (default): {median_skipna}"
)
Set skipna=False
median_no_skipna
=
data_with_nan.
median
(
skipna
=
False
)
(
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:
- Valid data: [10, 20, 30, 40, 50], 5 elements in total.
- The middle value after sorting: 30.
skipna=FalseWhen skipna=False, NaN is returned whenever any NaN is present.
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
]
)
(
"Monthly Income Data of Neighborhood Residents (Yuan):"
)
(
income_data
)
(
)
mean_income
=
income_data.
mean
(
)
median_income
=
income_data.
median
(
)
(
f
"Mean: {mean_income:.2f} Yuan"
)
(
f
"Median: {median_income} Yuan"
)
(
)
(
"Analysis:"
)
(
"The mean (10380 yuan) is pulled greatly upward by the extreme value (50000 yuan)."
)
(
"The median (4350 yuan) better reflects the true income level of most residents."
)
(
"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
- The median is insensitive to extreme values and is more robust than the mean.
- When the number of data points is even, the median is the average of the two middle numbers.
- When data has a clearly skewed distribution, the median reflects the center of the data better than the mean.
skipnaThe behavior of the parameters is the same as in mean().mean().
Summary
Series.median() It is an important function for describing central tendency. Its main features include:
- Not affected by extreme values, giving robust results.
- For an even number of elements, returns the average of the two middle elements.
- Especially useful in the analysis of data with skewed distributions such as income and housing prices.
- The syntax and parameters are the same as those of mean(),
mean()they are completely identical and easy to learn and use.
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.
Common Pandas functions