在 Numpy 中计算沿轴 0 的掩码数组元素的中位数
要计算沿特定轴的掩码数组元素的中位数,请在 Python Numpy 中使用 **MaskedArray.median()** 方法 -
- 轴使用“axis”参数设置
- 轴是计算中位数的轴。
- 默认值(None)是沿数组的扁平化版本计算中位数。
overwrite_input 参数,如果为 True,则允许使用输入数组 (a) 的内存进行计算。输入数组将被对 median 的调用修改。当您不需要保留输入数组的内容时,这将节省内存。将输入视为未定义,但它可能会被完全或部分排序。默认为 False。请注意,如果 overwrite_input 为 True,并且输入不是 ndarray,则会引发错误。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法创建一个包含 int 元素的数组
arr = np.array([[65, 68, 81], [93, 33, 76], [73, 88, 51], [62, 45, 67]])
print("Array...
", arr)创建一个掩码数组并将其中一些标记为无效 -
maskArr = ma.masked_array(arr, mask =[[1, 1, 0], [ 0, 0, 0], [0, 1, 0], [0, 1, 0]])
print("
Our Masked Array...
", maskArr)获取掩码数组的类型 -
print("
Our Masked Array type...
", maskArr.dtype)
获取掩码数组的维度 -
print("
Our Masked Array Dimensions...
",maskArr.ndim)获取掩码数组的形状 -
print("
Our Masked Array Shape...
",maskArr.shape)
获取掩码数组的元素数量 -
print("
Number of elements in the Masked Array...
",maskArr.size)要计算沿特定轴的掩码数组元素的中位数,请使用 MaskedArray.median() 方法。轴使用“axis”参数设置。轴是计算中位数的轴。默认值(None)是沿数组的扁平化版本计算中位数 -
resArr = np.ma.median(maskArr, axis = 0)
print("
Resultant Array..
.", resArr)示例
import numpy as np
import numpy.ma as 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...
", 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("
Our Masked Array...
", maskArr)
# Get the type of the masked array
print("
Our Masked Array type...
", maskArr.dtype)
# Get the dimensions of the Masked Array
print("
Our Masked Array Dimensions...
",maskArr.ndim)
# Get the shape of the Masked Array
print("
Our Masked Array Shape...
",maskArr.shape)
# Get the number of elements of the Masked Array
print("
Number of elements in the Masked Array...
",maskArr.size)
# To compute the median of the masked array elements along specific axis, use the MaskedArray.median() method in Python Numpy
# The axis is set using the "axis" parameter
# The axis is axis along which the medians are computed.
# The default (None) is to compute the median along a flattened version of the array.
resArr = np.ma.median(maskArr, axis = 0)
print("
Resultant Array..
.", 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.. . [73.0 33.0 71.5]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP