使用Numpy计算掩码数组沿指定轴的最大值
要计算掩码数组沿指定轴的最大值,可以使用Python Numpy中的**MaskedArray.max()**方法。该函数**max()**返回一个包含结果的新数组。如果指定了out,则返回out。轴使用“axis”参数设置。“axis”参数指定操作的轴。
out参数是用于放置结果的备用输出数组。必须与预期输出具有相同的形状和缓冲区长度。fill_value是用于填充掩码值的数值。如果为None,则使用maximum_fill_value()的输出。如果keepdims设置为True,则减少的轴将作为大小为一的维度保留在结果中。使用此选项,结果将与数组正确广播。
步骤
首先,导入所需的库:
import numpy as np import numpy.ma as ma
使用numpy.array()方法创建一个包含整型元素的数组:
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.max()方法。轴使用“axis”参数设置。“axis”参数指定操作的轴:
resArr = maskArr.max(axis = 1)
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 maximum of the masked array elements along a given axis, use the MaskedArray.max() method in Python Numpy
# The axis is set using the "axis" parameter
# The axis is the axis along which to operate
resArr = maskArr.max(axis = 1)
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.. . [81 93 73 67]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP