Get Median of NumPy Array in Python – np.median() Function (3 Examples)

In this Python tutorial you’ll learn how to use the np.median function.

Setting up the Examples

import numpy                         # Load numpy
x = np.array([[8, 2, 1, 7, 7, 5],    # Constructing a NumPy array in Python
              [4, 10, 5, 9, 1, 4]])
print(x)
# [[ 8  2  1  7  7  5]
#  [ 4 10  5  9  1  4]]

Example 1: Calculate Median of All Array Values in Python

print(np.median(x))                  # Computing the median of all values
# 5.0

Example 2: Calculate Median by Array Rows in Python

print(np.median(x, axis = 1))        # Computing the median by rows
# [6.  4.5]

Example 3: Calculate Median by Array Columns in Python

print(np.median(x, axis = 0))        # Computing the median by columns
# [6.  6.  3.  8.  4.  4.5]

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.
You need to agree with the terms to proceed

Menu
Top