将输入转换为至少具有一维的 NumPy 数组
要将输入转换为至少具有一维的数组,请在 Python NumPy 中使用 **ma.atleast_1d()** 方法。标量输入将转换为一维数组,而更高维度的输入将保留。它返回一个数组或数组列表,每个数组的 a.ndim >= 1。仅在必要时进行复制。该函数应用于 _data 和 _mask(如果有)。
掩码数组是标准 numpy.ndarray 和掩码的组合。掩码要么是 nomask,表示关联数组的任何值均无效,要么是布尔值的数组,用于确定关联数组的每个元素的值是否有效。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法创建一个包含整数元素的数组 -
arr = np.array([65, 68, 81]) print("Array...
", arr) print("
Array type...
", arr.dtype)
获取数组的维度 -
print("
Array Dimensions...
",arr.ndim)
创建一个掩码数组,并将其中一些标记为无效 -
maskArr = ma.masked_array(arr, mask =[[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)
使用 ma.atleast_1d() 方法将输入转换为至少具有一维的数组 -
print("
Result...
",np.atleast_1d(1, maskArr))
示例
# Python ma.MaskedArray - Convert inputs to arrays with at least one dimension 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]) 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, 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 convert inputs to arrays with at least one dimension, use the ma.atleast_1d() method in Python Numpy print("
Result...
",np.atleast_1d(1, maskArr))
输出
Array... [65 68 81] Array type... int64 Array Dimensions... 1 Our Masked Array [65 -- 81] Our Masked Array type... int64 Our Masked Array Dimensions... 1 Our Masked Array Shape... (3,) Elements in the Masked Array... 3 Result... [array([1]), masked_array(data=[65, --, 81], mask=[False, True, False], fill_value=999999)]
广告