Facebook Page Twitter Page LinkedIn Page
× NumPy Tutorial NumPy Resources

The NumPy median() function is used to compute the median along the specified axis. The median is calculated over the flattened array by default, otherwise over the specified axis.


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


a Required. Specify an array (array_like) containing numbers whose median is desired.
axis Optional. Specify axis or axes along which the medians are computed. The default is to compute the median of the flattened array..
out Optional. Specify output array for the result. The default is None. If provided, it must have the same shape as output.
overwrite_input Optional. If True, the input array will be modified. If overwrite_input is True and a is not already an ndarray, an error will be raised. Default is False.
keepdims Optional. If this is set to True, the reduced axes are left in the result as dimensions with size one. With this option, the result will broadcast correctly against the input array.

Return Value

Returns an array containing the median values when out=None, otherwise returns a reference to the output array.

Example: median of all values

In the below example, median() function is used to calculate median of all values present in the array.

import numpy as np
Arr = np.array([[10,20],[30, 40]])

print("Array is:")

#median of all values
print("\nMedian of values:", np.median(Arr))

The output of the above code will be:

Array is:
[[10 20]
 [30 40]]

Median of values: 25.0

Example: median() with axis parameter

When axis parameter is provided, median is calculated over the specified axes. Consider the following example.

import numpy as np
Arr = np.array([[10,20,500],[30,40,400], [100,200,300]])

print("Array is:")

#median along axis=0
print("\nMedian along axis=0")
print(np.median(Arr, axis=0))

#median along axis=1
print("\nMedian along axis=1")
print(np.median(Arr, axis=1))

The output of the above code will be:

Array is:
[[ 10  20 500]
 [ 30  40 400]
 [100 200 300]]

Median along axis=0
[ 30.  40. 400.]

Median along axis=1
[ 20.  40. 200.]

❮ NumPy - Functions