Thursday, November 20, 2025
HomeLanguagesnumpy.median() in Python

numpy.median() in Python

numpy.median(arr, axis = None) : Compute the median of the given data (array elements) along the specified axis.

How to calculate median?

  • Given data points.
  • Arrange them in ascending order
  • Median = middle term if total no. of terms are odd.
  • Median = Average of the terms in the middle (if total no. of terms are even)

Parameters :
arr : [array_like]input array.
axis : [int or tuples of int]axis along which we want to calculate the median. Otherwise, it will consider arr to be flattened(works on all the axis). axis = 0 means along the column and axis = 1 means working along the row.
out : [ndarray, optional] Different array in which we want to place the result. The array must have the same dimensions as expected output.
dtype : [data-type, optional]Type we desire while computing median.

Results : Median of the array (a scalar value if axis is none) or array with median values along specified axis.

Code #1:




# Python Program illustrating 
# numpy.median() method 
    
import numpy as np
    
# 1D array 
arr = [20, 2, 7, 1, 34]
  
print("arr : ", arr) 
print("median of arr : ", np.median(arr))
   


Output :

arr :  [20, 2, 7, 1, 34]
median of arr :  7.0

 
Code #2:




# Python Program illustrating 
# numpy.median() method  
import numpy as np
    
# 2D array 
arr = [[14, 17, 12, 33, 44],  
       [15, 6, 27, 8, 19], 
       [23, 2, 54, 1, 4, ]] 
    
# median of the flattened array 
print("\nmedian of arr, axis = None : ", np.median(arr)) 
    
# median along the axis = 0 
print("\nmedian of arr, axis = 0 : ", np.median(arr, axis = 0)) 
   
# median along the axis = 1 
print("\nmedian of arr, axis = 1 : ", np.median(arr, axis = 1))
  
out_arr = np.arange(3)
print("\nout_arr : ", out_arr) 
print("median of arr, axis = 1 : ", 
      np.median(arr, axis = 1, out = out_arr))


Output :

median of arr, axis = None :  15.0

median of arr, axis = 0 :  [15.  6. 27.  8. 19.]

median of arr, axis = 1 :  [17. 15.  4.]

out_arr :  [0 1 2]
median of arr, axis = 1 :  [17 15  4]
RELATED ARTICLES

Most Popular

Dominic
32404 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6777 POSTS0 COMMENTS
Nicole Veronica
11925 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11994 POSTS0 COMMENTS
Shaida Kate Naidoo
6905 POSTS0 COMMENTS
Ted Musemwa
7162 POSTS0 COMMENTS
Thapelo Manthata
6861 POSTS0 COMMENTS
Umr Jansen
6846 POSTS0 COMMENTS