Python NumPy Median() Function with Examples

In this Python NumPy tutorial, we will learn how to get median of a NumPy array in Python.

Python numpy median() function

To find the median of a numpy array in Python, we use the Python numpy.median() function. In Python, this is a mathematical function and it is used to compute the median of the elements in an array.

This method is available in the NumPy package module and always returns the median of the numpy array value as an output. If you are using a multidimensional array then you can also get the median value of each column and row.

Syntax:

Let’s have a look at the Syntax and understand the working of Python numpy.median() function

numpy.median
            (
             a,
             axis=None,
             out=None,
             overwrite_input=False,
             keepdims=False
            )
  • This Syntax contains several parameters
    • a: This parameter specifies the input array on which we want to operate on.
    • axis: This parameter indicates the axis on which we want to calculate the median along with the flattened input array. If the axis is 0 then the direction down the rows and if the axis is 1 then the direction down column-wise.
    • out: It is an optional parameter and it is used to store the result of numpy.median() function and by default it takes none value.
    • keepdims: This parameter defines the dimension of the input array and if the value is ‘True’ the axes which are reduced are left in the output.

Example:

Let’s take an example and check how to use the numpy.median() function in Python

Source Code:

import numpy as np

new_arr=np.array([67,89,113,145,167])
new_output= np.median(new_arr)
print("Median of an array:",new_output)

In the above code, we imported the numpy library and then initialize an array by using the numpy.array() function and now we have to find the median of the input array. To do this we are going to use the numpy.median() function.

In the above array, we have an odd number of terms in ascending order. It will calculate the array median=middle term.

Here is the implementation of the following given code

Python numpy median
Python numpy median

Read: Python NumPy Replace + Examples

Python Numpy Median

The median is a measure of central tendency that is commonly used in statistics to find the middle value of a dataset. In NumPy, there are several ways to compute the median of an array or a sequence of numbers. These methods include using the median() function, partitioning, percentile(), etc.

Method-1: Python numpy median using the np.median() function

The easiest way to calculate the median in NumPy is to use the np.median() function, which calculates the median of an array along a specified axis.

# Import the NumPy library
import numpy as np

# Create a one-dimensional array containing the values 67, 89, 113, 145, and 167
new_arr = np.array([67, 89, 113, 145, 167])

# Calculate the median of the array using the np.median() function
new_output = np.median(new_arr)

# Print the calculated median using the print() function, along with a message
print("Median of an array:", new_output)

The above code imports the NumPy library and creates a one-dimensional array new_arr containing the values 67, 89, 113, 145, and 167.

  • The code then calculates the median of the array using the np.median() function and assigns the result to the variable new_output.
  • Finally, the code prints the calculated median using the print() function, along with the message “Median of an array:”.
Python numpy median
Python numpy median

Method-2: Python numpy median using np.sort() function

Another way to calculate the median in NumPy is to use the np.sort() function to sort the array, and then take the middle element(s) as the median.

# Import the NumPy library
import numpy as np

# Create a NumPy array containing the values 1, 3, 2, 4, and 5
arr = np.array([1, 3, 2, 4, 5])

# Sort the array using the np.sort() function
sorted_arr = np.sort(arr)

# Get the length of the array
n = len(arr)

# Check if the length of the array is even or odd, and calculate the median accordingly
if n % 2 == 0:
    median = (sorted_arr[n//2-1] + sorted_arr[n//2])/2
else:
    median = sorted_arr[n//2]

# Print the calculated median, along with a message
print(median) 

The above code calculates the median of a given NumPy array. To do this, it first sorts the array in ascending order using the np.sort() function.

  • Then, it checks if the length of the array is even or odd by checking if the remainder of n % 2 is 0 or not, where n is the length of the array. If the length is even, the code calculates the median by taking the average of the two middle values in the sorted array.
  • If the length is odd, the code calculates the median by taking the middle value in the sorted array. Finally, the code prints the calculated median value using the print() function.
Output: 3.0

Method-3: Python numpy median using np.partition() function

Similar to Method 2, this method first partitions the array using numpy.partition(), then uses indexing to extract the median value.

import numpy as np

# Create a NumPy array
array = np.array([1, 2, 3, 4, 5])

# Use np.partition() to partition the array around its median
partitioned_array = np.partition(array, len(array) // 2)

# Get the length of the partitioned array
n = len(partitioned_array)

# Calculate the median of the partitioned array
# If the length is odd, the median is the middle value
# If the length is even, the median is the average of the two middle values
median = partitioned_array[n // 2] if n % 2 != 0 else (partitioned_array[n // 2 - 1] + partitioned_array[n // 2]) / 2

# Print the median
print(median)

The above code imports the NumPy library and creates an array with values [1, 2, 3, 4, 5].

  • It then partitions the array using np.partition() around its median value, and calculates the median value of the partitioned array. If the partitioned array has an odd length, the median is the middle value.
  • If the partitioned array has an even length, the median is the average of the two middle values. Finally, the code prints the median value to the console.
Output: 3

Method-4: Python numpy median using numpy.mean() of the two middle values

Another way to calculate the median of a NumPy array is to find the two middle values (if the length of the array is even) and take their average using numpy.mean().

import numpy as np

# Create a NumPy array
arr = np.array([11, 12, 13, 14, 15])

# Get the length of the array
n = len(arr)

# Sort the array
sorted_arr = np.sort(arr)

# Calculate the median of the sorted array
# If the length is odd, the median is the middle value
# If the length is even, the median is the average of the two middle values
median = (sorted_arr[(n - 1) // 2] + sorted_arr[n // 2]) / 2

# Print the median
print(median)

In the above code, the input array arr is sorted using np.sort(), and then the median value of the sorted array is calculated using a formula.

  • If the length of the array is odd, the median is simply the middle value of the sorted array. If the length of the array is even, the median is the average of the two middle values of the sorted array.
  • Finally, the median value is printed to the console using print().
Output: 13.0

Method-5: Python numpy median using numpy.percentile()

numpy.percentile() is a function that returns the specified percentile(s) of an array. To find the median, we can use the 50th percentile.

import numpy as np

# Create a NumPy array
arr = np.array([11, 12, 13, 14, 15])

# Calculate the median using the np.percentile() function
# The second argument to np.percentile() specifies the percentile value to compute,
# so setting it to 50 gives the median
median = np.percentile(arr, 50)

# Print the median
print(median)

In the above code, the median value of the input array arr is computed using the np.percentile() function.

  • This function takes two arguments: the array to compute the percentile on, and the percentile value to compute. Setting the second argument to 50 computes the median value. Finally, the median value is printed to the console using print().
Output: 13.0

Method-6: Python numpy median using numpy.argpartition()

This method uses numpy.argpartition() to partition the array around its median and get the indices of the partitioned elements. Then it calculates the median using those indices and the values in the array.

import numpy as np

# Create a NumPy array
arr = np.array([21, 22, 23, 24, 25])

# Partition the array around its median using np.argpartition()
# This returns the indices that would partition the array
# The second argument to np.argpartition() specifies the index of the partition point
partitioned_indices = np.argpartition(arr, len(arr) // 2)

# Get the length of the partitioned indices
n = len(partitioned_indices)

# Calculate the median of the partitioned array
# If the length is odd, the median is the middle value
# If the length is even, the median is the average of the two middle values
median = arr[partitioned_indices[n // 2]] if n % 2 != 0 else (arr[partitioned_indices[n // 2 - 1]] + arr[partitioned_indices[n // 2]]) / 2

# Print the median
print(median)

In the above code, the input array arr is partitioned around its median using np.argpartition().

  • This function returns the indices that would partition the array, so we use these indices to calculate the median value of the partitioned array.
  • If the length of the partitioned array is odd, the median is simply the middle value. If the length of the partitioned array is even, the median is the average of the two middle values. Finally, the median value is printed to the console using print().
Output: 23

Python numpy median example

  • In this section, we will discuss how to use the numpy.median() function in Python.
  • In Python, the numpy median is used to generate the median value in the NumPy array and this function involves many parameters namely axis.keepdims and it is also used for specifying the data type that a user needs to be operand on.
  • In this example, we will use the axis and keepdims parameter to check how to get the median value of the numpy array.

Example:

Let’s take an example and check how to use the numpy.median() function in Python

Source Code:

import numpy as np

new_arr=np.array([[67,89,113,145,167],
                 [14,16,18,20,24],
                 [33,45,67,89,91]])
new_output= np.median(new_arr,axis=0)
new_output2= np.median(new_arr,axis=1,)
print("Axis row-wise median:",new_output)
print("Axis column-wise median",new_output2)

In the above program, we have used the axis parameter in numpy.median() function and it will calculate the row and column medians.

Here is the execution of the following given code

Python numpy median example
Python numpy median example

Also, take a look at some more Python NumPy tutorials.

In this Python NumPy tutorial, we have learned how to get median of a NumPy array in Python.