在 Numpy 中计算掩码数组元素的中位数
要计算掩码数组元素的中位数,请使用Python Numpy 中的方法。MaskedArray.median()
overwrite_input 参数,如果为 True,则允许使用输入数组 (a) 的内存进行计算。输入数组将通过调用中值来修改。当您不需要保留输入数组的内容时,这将节省内存。将输入视为未定义,但它可能会完全或部分排序。默认为假。请注意,如果 overwrite_input 为 True,并且输入还不是 ndarray,则会引发错误。
脚步
首先,导入所需的库 -
import numpy as npimportnumpy.maas ma
使用该方法创建一个包含 int 元素的数组-numpy.array()
arr = np.array([[65, 68, 81], [93, 33, 76], [73, 88, 51], [62, 45, 67]])print("Array...\n", arr)
创建一个屏蔽数组并将其中一些屏蔽为无效 -
maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])print("\nOur Masked Array...\n", maskArr)
获取掩码数组的类型 -
print("\nOur Masked Array type...\n", maskArr.dtype)
获取 Masked Array 的尺寸 -
print("\nOur Masked Array Dimensions...\n",maskArr.ndim)
获取蒙面阵列的形状 -
print("\nOur Masked Array Shape...\n",maskArr.shape)
获取 Masked Array 的元素数量 -
print("\nNumber of elements in the Masked Array...\n",maskArr.size)
要计算掩码数组元素的中位数,请使用Python Numpy 中的方法 -MaskedArray.median()
resArr = np.ma.median(maskArr)print("\nResultant Array..\n.", resArr)
示例
import numpy as np输出结果importnumpy.maas ma
# Create an array with int elements using the numpy.array() method
arr = np.array([[65, 68, 81], [93, 33, 76], [73, 88, 51], [62, 45, 67]])
print("Array...\n", arr)
# Create a masked array and mask some of them as invalid
maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])
print("\nOur Masked Array...\n", maskArr)
# Get the type of the masked array
print("\nOur Masked Array type...\n", maskArr.dtype)
# Get the dimensions of the Masked Array
print("\nOur Masked Array Dimensions...\n",maskArr.ndim)
# Get the shape of the Masked Array
print("\nOur Masked Array Shape...\n",maskArr.shape)
# Get the number of elements of the Masked Array
print("\nNumber of elements in the Masked Array...\n",maskArr.size)
# To compute the median of the masked array elements, use the MaskedArray.median() method in Python Numpy
resArr = np.ma.median(maskArr)
print("\nResultant Array..\n.", resArr)
Array...[[65 68 81]
[93 33 76]
[73 88 51]
[62 45 67]]
Our Masked Array...
[[-- -- 81]
[93 33 76]
[73 -- 51]
[62 -- 67]]
Our Masked Array type...
int64
Our Masked Array Dimensions...
2
Our Masked Array Shape...
(4, 3)
Number of elements in the Masked Array...
12
Resultant Array..
. 70.0
以上是 在 Numpy 中计算掩码数组元素的中位数 的全部内容, 来源链接: utcz.com/z/297113.html