返回 NumPy 中掩码数组的每个四舍五入后的元素
要返回每个四舍五入后的元素,请在 Python NumPy 中使用 **ma.MaskedArray.around()** 方法。decimals 参数是要舍入到的十进制位数(默认值:0)。如果 decimals 为负数,则它指定小数点左侧的位置数。
out 参数是放置结果的备用输出数组。它必须与预期输出具有相同的形状,但如果需要,输出值的类型将被强制转换。有关详细信息,请参阅输出类型确定。
around() 方法返回一个与 a 类型相同的数组,其中包含四舍五入的值。除非指定了 out,否则会创建一个新数组。返回对结果的引用。
步骤
首先,导入所需的库:
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.around() 方法:
print("
Result...
", np.around(maskArr))
示例
# Python ma.MaskedArray - Return each element of the masked array rounded import numpy as np import numpy.ma as ma # Create an array with int elements using the numpy.array() method arr = np.array([[55.50, 85.35, 68.78, 84], [67.96, 33.35, 39.76,53.20]]) 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 =[[1, 1, 0, 0], [0, 1, 0, 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 return each element rounded, use the ma.MaskedArray.around() method in Numpy. print("
Result...
", np.around(maskArr))
输出
Array... [[55.5 85.35 68.78 84. ] [67.96 33.35 39.76 53.2 ]] Array type... float64 Array Dimensions... 2 Our Masked Array [[-- -- 68.78 84.0] [67.96 -- 39.76 53.2]] Our Masked Array type... float64 Our Masked Array Dimensions... 2 Our Masked Array Shape... (2, 4) Elements in the Masked Array... 8 Result... [[-- -- 69.0 84.0] [68.0 -- 40.0 53.0]]
广告