使用 NumPy 中的 torecords() 将掩码数组转换为灵活类型数组
要将掩码数组转换为灵活类型数组,请使用 **ma.MaskedArray.torecords()**。返回的灵活类型数组将有两个字段
_data 字段存储数组的 _data 部分。
_mask 字段存储数组的 _mask 部分。
返回一个新的具有两个字段的灵活类型 ndarray - 第一个元素包含一个值,第二个元素包含相应的掩码布尔值。返回的记录形状与 self.shape 匹配。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法创建一个包含整数元素的数组 -
arr = np.array([[49, 85, 45], [67, 33, 59]]) print("Array...
", arr) print("
Array type...
", arr.dtype)
获取数组的维度 -
print("Array Dimensions...
",arr.ndim)
创建一个掩码数组并将其中的某些元素标记为无效 -
maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 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("
Elements in the Masked Array...
",maskArr.size)
要将掩码数组转换为灵活类型数组,请使用 NumPy 中的 ma.MaskedArray.torecords() 方法。返回的灵活类型数组将有两个字段:_data 字段存储数组的 _data 部分 -
print("
Result of the transformation...
",maskArr.torecords())
示例
# Python - Transform a masked array into a flexible-type array with MaskedArray.torecords() import numpy as np import numpy.ma as ma # Create an array with int elements using the numpy.array() method arr = np.array([[49, 85, 45], [67, 33, 59]]) print("Array...
", arr) print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Create a masked array and mask some of them as invalid maskArr = ma.masked_array(arr, mask =[[0, 0, 1], [ 0, 1, 0]]) print("
Our Masked Array
", maskArr) 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("
Elements in the Masked Array...
",maskArr.size) # To transform a masked array into a flexible-type array, use the ma.MaskedArray.torecords() method in Numpy # The flexible type array that is returned will have two fields: the _data field stores the _data part of the array. #, the _mask field stores the _mask part of the array. print("
Result of the transformation...
",maskArr.torecords())
输出
Array... [[49 85 45] [67 33 59]] Array type... int64 Array Dimensions... 2 Our Masked Array [[49 85 --] [67 -- 59]] Our Masked Array type... int64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (2, 3) Elements in the Masked Array... 6 Result of the transformation... [[(49, False) (85, False) (45, True)] [(67, False) (33, True) (59, False)]]
广告