返回 NumPy 中掩码数组的每个元素,四舍五入到给定的小数位数。
要将每个元素四舍五入到指定的小数位数,请在 NumPy 中使用 **ma.MaskedArray.around()** 方法。使用“**decimals**”参数设置要四舍五入的小数位数。
decimals 参数是要四舍五入到的十进制位数(默认值:0)。如果 decimals 为负数,则它指定小数点左侧的位置数。
out 参数是放置结果的备用输出数组。它必须与预期输出具有相同的形状,但如果需要,输出值的类型将被强制转换。有关详细信息,请参阅输出类型确定。
around() 方法返回一个与 a 类型相同的数组,其中包含四舍五入的值。除非指定了 out,否则将创建一个新数组。返回对结果的引用。
步骤
首先,导入所需的库 -
import numpy as np import numpy.ma as ma
使用 numpy.array() 方法创建包含 int 元素的数组 -
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)获取数组的维度 -
print("Array Dimensions...
",arr.ndim)
创建一个掩码数组并将其中一些标记为无效 -
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)获取掩码数组的维度 -
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() 方法。使用“decimals”参数设置要四舍五入的小数位数 -
print("
Result...
", np.around(maskArr, decimals = 1))示例
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 to the given number of decimals, use the ma.MaskedArray.around() method in Numpy.
# Set the number of decimal places to round using the "decimals" parameter
print("
Result...
", np.around(maskArr, decimals = 1))输出
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... [[-- -- 68.8 84.0] [68.0 -- 39.8 53.2]]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP