📜  计算扁平 NumPy 数组的中位数

📅  最后修改于: 2022-05-13 01:55:52.135000             🧑  作者: Mango

计算扁平 NumPy 数组的中位数

在本文中,我们将讨论如何计算扁平数组的中位数。中位数基本上是将数组的下半部分与数组的上半部分分开的值。

例子:

它可以使用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