NumPy Median Function

PythonPythonBeginner
Practice Now

Introduction

NumPy is a Python library that is used for working with arrays. It also supports mathematical operations on arrays. One such mathematical operation is finding the median of an array. The median is the middle value of a set of data. It is used to represent the average of a set of numbers and is not affected by outliers. In this lab, we will learn how to use the NumPy median function.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.

Import NumPy library

Before we use the NumPy library, we first need to import it.

import numpy as np

Create a 1D array

Let's create a one-dimensional array using the numpy.array() method, which will be used as input for finding the median.

a = np.array([26, 2, 73, 13, 34])

Find the median of a 1D array

We use the numpy.median() method to find the median of an array. We don't need to specify any axis since it is a 1D array.

median = np.median(a)
print("The median of the 1D array is:", median)

Output:

The median of the 1D array is: 26.0

Create a 2D array

Now let's create a two-dimensional array with different sets of input values.

inp = np.array([[1, 17, 19, 33, 49], [14, 6, 87, 8, 19], [34, 2, 54, 4, 7]])

Find the median of a 2D array when axis=None

Now we will use numpy.median() method to find the median of a 2D array.

When axis=None, it returns the median of all elements in the array.

median = np.median(inp)
print("The median of array when axis=None :", median)

Output:

The median of array when axis=None : 17.0

Find the median of a 2D array when axis=0

When axis=0, it returns the median along the column of the 2D array.

median = np.median(inp, axis=0)
print("The median of array when axis=0 :", median)

Output:

The median of array when axis=0 : [14.  6. 54.  8. 19.]

Find the median of a 2D array when axis=1

When axis=1, it returns the median along the row of the 2D array.

median = np.median(inp, axis=1)
print("The median of array when axis=1 :", median)

Output:

The median of array when axis=1 : [19. 14.  7.]

Summary

In this lab, we learned about the NumPy library and how it can be used for finding the median of an array. We also covered the syntax and parameter of the numpy.median() function. Additionally, we looked at examples of finding median in a one-dimensional and two-dimensional array.

Other Python Tutorials you may like