# Compute the median of the flattened NumPy array

• Last Updated : 05 Sep, 2020

In this article, we will discuss how to compute the median of the flattened array. Median is basically that value that separates the lower half of the array with the higher half of array.

Example:

If there are odd numbers in an array.
A = [1,2,3,4,5,6,7]
Then the median element will be 7+1/2= 4th element of the array.
Hence the Median in this array is 4.

If there are even numbers in an array
A = [1,2,3,4,5,6,7,8]
Then the median element will be average of two middle elements.
Here it will be an average of 4th and 5th element of the array that is 4+1/2 =4.5.

It can be calculated using the numpy.median() function in Python. This function computes the median of the given data (array elements) along the specified axis.

Syntax:

numpy.median(arr, axis = None)

Example 1: Odd no of elements

## Python3

 # importing numpy as libraryimport numpy as np    # creating 1 D array with odd no of # elementsx_odd = np.array([1, 2, 3, 4, 5, 6, 7])print("\nPrinting the Original array:")print(x_odd)  # calculating medianmed_odd = np.median(x_odd)print("\nMedian of the array that contains \odd no of elements:")print(med_odd)

Output:

Printing the Original array:
[1 2 3 4 5 6 7]

Median of the array that contains odd no of elements:
4.0

Example 2: Even no of elements:

## Python3

 # importing numpy as libraryimport numpy as np    # creating 1 D array with even no of # elementsx_even = np.array([1, 2, 3, 4, 5, 6, 7, 8])print("\nPrinting the Original array:")print(x_even)  # calculating medianmed_even = np.median(x_even)print("\nMedian of the array that contains \even no of elements:")print(med_even)

Output:

Printing the Original array:
[1 2 3 4 5 6 7 8]

Median of the array that contains even no of elements:
4.5

My Personal Notes arrow_drop_up