Get Median of Array with np.median Function of NumPy Library in Python (3 Examples)


In this tutorial you’ll learn how to apply the np.median function in the Python programming language.

The tutorial consists of these topics:

Let’s get started:


Example Data & Libraries

First, we need to load the NumPy library.

import numpy as np                             # Import NumPy library

As a next step, we’ll also have to define some data that we can use in the examples below:

my_array = np.array([[1, 2, 3], [4, 5, 6]])    # Create example array
print(my_array)                                # Print example array
# [[1 2 3]
#  [4 5 6]]

The previous output of the Python console shows the structure of our exemplifying data – It’s a NumPy array containing six different values.


Example 1: Median of All Values in NumPy Array

Example 1 explains how to calculate the median of all values in a NumPy array.

For this task, we can use the median function that is provided by the NumPy library:

print(np.median(my_array))                     # Get median of all array values
# 3.5

As you can see, the median of all values in our data is equal to 3.5.


Example 2: Median of Columns in NumPy Array

In Example 2, I’ll illustrate how to compute the median for each column in our example array.

For this, we have to set the axis argument to be equal to 0:

print(np.median(my_array, axis = 0))           # Get median of array columns
# [2.5 3.5 4.5]


Example 3: Median of Rows in NumPy Array

Example 3 demonstrates how to find the median value for each row in our array.

For this, we have to specify axis equal to 1 within the median function:

print(np.median(my_array, axis = 1))           # Get median of array rows
# [2. 5.]


Video, Further Resources & Summary

Do you need further info on the Python code of this tutorial? Then I can recommend watching the following video instruction on my YouTube channel. In the video, I show the Python code of this article in a programming session.


The YouTube video will be added soon.


Furthermore, you might want to have a look at some of the related tutorials on this website. I have released several posts already:


At this point you should have learned how to use the np.median function to get the median value of an array in Python. If you have additional questions, please let me know in the comments below.


Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.

Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.