计算扁平 NumPy 数组的中位数
在本文中,我们将讨论如何计算扁平数组的中位数。中位数基本上是将数组的下半部分与数组的上半部分分开的值。
例子:
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.
它可以使用Python中的 numpy.median()函数来计算。此函数计算给定数据(数组元素)沿指定轴的中位数。
句法:
numpy.median(arr, axis = None)
示例 1:奇数个元素
Python3
# importing numpy as library
import numpy as np
# creating 1 D array with odd no of
# elements
x_odd = np.array([1, 2, 3, 4, 5, 6, 7])
print("\nPrinting the Original array:")
print(x_odd)
# calculating median
med_odd = np.median(x_odd)
print("\nMedian of the array that contains \
odd no of elements:")
print(med_odd)
Python3
# importing numpy as library
import numpy as np
# creating 1 D array with even no of
# elements
x_even = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print("\nPrinting the Original array:")
print(x_even)
# calculating median
med_even = np.median(x_even)
print("\nMedian of the array that contains \
even no of elements:")
print(med_even)
输出:
Printing the Original array:
[1 2 3 4 5 6 7]
Median of the array that contains odd no of elements:
4.0
示例 2:即使没有元素:
Python3
# importing numpy as library
import numpy as np
# creating 1 D array with even no of
# elements
x_even = np.array([1, 2, 3, 4, 5, 6, 7, 8])
print("\nPrinting the Original array:")
print(x_even)
# calculating median
med_even = np.median(x_even)
print("\nMedian of the array that contains \
even no of elements:")
print(med_even)
输出:
Printing the Original array:
[1 2 3 4 5 6 7 8]
Median of the array that contains even no of elements:
4.5