Compute the median of the flattened NumPy array
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.
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.
numpy.median(arr, axis = None)
Example 1: Odd no of elements
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:
Printing the Original array: [1 2 3 4 5 6 7 8] Median of the array that contains even no of elements: 4.5
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course