在NumPy中将数组元素舍入到最接近的整数


要将数组元素舍入到最接近的整数,请在Python NumPy中使用**numpy.rint()**方法。对于正好位于舍入后的十进制值之间的值,NumPy会舍入到最接近的偶数值。

out 是存储结果的位置。如果提供,则其形状必须与输入广播到的形状相同。如果不提供或为 None,则返回一个新分配的数组。元组(仅可能作为关键字参数)的长度必须等于输出的数量。

条件在输入上进行广播。在条件为 True 的位置,out 数组将设置为 ufunc 结果。在其他地方,out 数组将保留其原始值。请注意,如果通过默认的 out=None 创建未初始化的 out 数组,则其中条件为 False 的位置将保持未初始化状态。

步骤

首先,导入所需的库:

import numpy as np

使用 array() 方法创建一个浮点型数组:

arr = np.array([50.8, 120.3, 200.7, 320.1, 450.4, 500.6])

显示数组:

print("Array...
", arr)

获取数组的类型:

print("
Our Array type...
", arr.dtype)

获取数组的维度:

print("
Our Array Dimension...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

要将数组元素舍入到最接近的整数,请在Python NumPy中使用numpy.rint()方法。对于正好位于舍入后的十进制值之间的值,NumPy会舍入到最接近的偶数值:

print("
Result (rounded)...
",np.rint(arr))

示例

import numpy as np

# Create an array with float type using the array() method
arr = np.array([50.8, 120.3, 200.7, 320.1, 450.4, 500.6])

# Display the array
print("Array...
", arr) # Get the type of the array print("
Our Array type...
", arr.dtype) # Get the dimensions of the Array print("
Our Array Dimension...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # To round elements of the array to the nearest integer, use the numpy.rint() method in Python Numpy # For values exactly halfway between rounded decimal values, NumPy rounds to the nearest even value. print("
Result (rounded)...
",np.rint(arr))

输出

Array...
[ 50.8 120.3 200.7 320.1 450.4 500.6]

Our Array type...
float64

Our Array Dimension...
1

Our Array Shape...
(6,)

Result (rounded)...
[ 51. 120. 201. 320. 450. 501.]

更新于:2022年2月8日

8K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.