numpy.median() in Python

The Python numpy.median() function calculates the median of given data along the specified axis.

Basic Syntax

Following is the basic syntax for numpy.median() function in Python:

numpy.median(arr, axis=None, out=None, overwrite_input=False, keepdims=False)

And the parameters are:

Parameter Description
arr [array-like] The input array
axis [default = None, OPTIONAL] int or sequence of int for the axis
out [default = None, OPTIONAL] different array must be with same dimension to place the result.

Return Value

This function returns a scalar value if axis = None or median of the array along given axis.

Example

Following are the examples:

Example 1

# Python Program to illusrate numpy.median() function   
import numpy as np 
    
my_array = [[1, 2, 3],   
       [4, 5, 6],  
       [7, 8, 9]]  
    
# Flattened array median  
print("\nThe Median, axis = None: ", np.median(my_array))  
    
# The Median along the axis = 0  
print("\nMedian, axis = 0: ", np.median(my_array, axis = 0))  
   
# median along the axis = 1  
print("\nMedian, axis = 1: ", np.median(my_array, axis = 1))

The output for the above program is as given below:

The Median, axis = None: 5.0
Median, axis = 0: [ 4., 5., 6.]
Median, axis = 1: [ 2., 5., 8.]

Example 2

# Python Program to illustrate numpy.median() function 
	
import numpy as np 
	
# 1D array 
my_array = [10, 20, 30, 40, 50, 60, 70, 80, 90] 

print("my_array : ", my_array) 
print("median of my_array : ", np.median(my_array)) 

# 1D array 
my_array2 = [15,69, 78,40,56] 

print("my_array2 : ", my_array2) 
print("median of my_array2 : ", np.median(my_array2)) 

The output for the above program is as given below:

my_array : [10, 20, 30, 40, 50, 60, 70, 80, 90]
median of my_array : 50.0
my_array2 : [15, 69, 78, 40, 56]
median of my_array : 56.0