使用NumPy从数组创建布尔掩码
要从数组创建布尔掩码,请在Python NumPy中使用**ma.make_mask()**方法。该函数可以接受任何可转换为整数的序列或nomask。不需要内容必须是0和1,值为0被解释为False,其他所有值被解释为True。
dtype是输出掩码的数据类型。默认情况下,输出掩码的dtype为MaskType(bool)。如果dtype是灵活的,则每个字段都有一个布尔dtype。当m为nomask时,此参数将被忽略,在这种情况下,始终返回nomask。
步骤
首先,导入所需的库:
import numpy as np import numpy.ma as ma
使用Python NumPy中的numpy.zeros()方法创建一个包含零的数组:
arr = np.zeros(7) print("Array...
", arr)
要从数组创建布尔掩码,请在Python NumPy中使用ma.make_mask()方法:
print("
Masked Array...
", ma.make_mask(arr))
数组类型:
print("
Array type...
", arr.dtype)
获取数组的维度:
print("
Array Dimensions...
",arr.ndim)
获取数组的形状:
print("
Our Array Shape...
",arr.shape)
获取数组的元素个数:
print("
Elements in the Array...
",arr.size)
示例
import numpy as np import numpy.ma as ma # Create an array with zeros using the numpy.zeros() method in Python Numpy arr = np.zeros(7) print("Array...
", arr) # To Create a boolean mask from an array, use the ma.mask_mask() method in Python Numpy print("
Masked Array...
", ma.make_mask(arr)) # Type of Array print("
Array type...
", arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size)
输出
Array... [0. 0. 0. 0. 0. 0. 0.] Masked Array... False Array type... float64 Array Dimensions... 1 Our Array Shape... (7,) Elements in the Array... 7
广告