6.2 C
London
Thursday, December 19, 2024
HomePandas in PythonDataFrame Functions in PythonHow to Calculate the Median in Pandas (With Examples)

How to Calculate the Median in Pandas (With Examples)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

You can use the median() function to find the median of one or more columns in a pandas DataFrame:

#find median value in specific column
df['column1'].median()

#find median value in several columns
df[['column1', 'column2']].median()

#find median value in every numeric column
df.median()

The following examples show how to use this function in practice with the following pandas DataFrame:

#create DataFrame
df = pd.DataFrame({'player': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
                   'points': [25, pd.NA, 15, 14, 19, 23, 25, 29],
                   'assists': [5, 7, 7, 9, 12, 9, 9, 4],
                   'rebounds': [11, 8, 10, 6, 6, 5, 9, 12]})

#view DataFrame
df

	player	points	assists	rebounds
0	A	25	5	11
1	B	NA	7	8
2	C	15	7	10
3	D	14	9	6
4	E	19	12	6
5	F	23	9	5
6	G	25	9	9
7	H	29	4	12

Example 1: Find Median of a Single Column

The following code shows how to find the median value of a single column in a pandas DataFrame:

#find median value of points column
df['points'].median()

23.0

The median value in the points column is 23

Note that by default, the median() function ignores any missing values when calculating the median.

Example 2: Find Median of Multiple Columns

The following code shows how to find the median value of multiple columns in a pandas DataFrame:

#find median value of points and rebounds columns
df[['points', 'rebounds']].median()

points      23.0
rebounds     8.5
dtype: float64

Example 3: Find Median of All Numeric Columns

The following code shows how to find the median value of all numeric columns in a pandas DataFrame:

#find median value of all numeric columns
df.median()

points      23.0
assists      8.0
rebounds     8.5
dtype: float64

Additional Resources

How to Calculate the Mean of Columns in Pandas
How to Calculate the Sum of Columns in Pandas
How to Find the Max Value of Columns in Pandas

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories