NumPy around()

around() 函数将数组的元素四舍五入到最接近的整数。

示例

import numpy as np

# create an array with decimal values
array1 = np.array([1.234, 2.678, 3.543, 4.876, 5.192])

# round the elements using around() result = np.around(array1)
print(result) # Output : [1. 3. 4. 5. 5.]

around() 语法

around() 的语法是

numpy.round(array, decimals=0, out=None)

around() 参数

around() 函数接受一个参数

  • array - 需要四舍五入的元素的输入数组
  • decimal (可选) - array 的元素四舍五入到的小数位数
  • out (可选) - 用于存储结果的输出数组。

around() 返回值

around() 函数返回一个带有四舍五入值的新数组。


示例 1:将数组元素四舍五入到最接近的整数

import numpy as np

# create a 2D array with decimal values
array1 = np.array([[1.2, 2.7, 3.5],
                                [4.8, 5.1, 6.3],
                                [7.2, 8.5, 9.9]])

# round the elements to the nearest integer using np.around() result = np.around(array1)
print("Rounded array:") print(result)

输出

Rounded array:
[[ 1.  3.  4.]
 [ 5.  5.  6.]
 [ 7.  8. 10.]]

在上面的示例中,np.around() 函数将数组的元素四舍五入到最接近的整数。

但是,即使四舍五入后,数组的数据类型仍然是 float64。这就是输出中出现小数点的原因。

如果您希望输出是整数且没有小数点,可以使用 astype() 将四舍五入后的数组数据类型转换为 int,如下所示:

rounded_array = np.around(array1).astype(int)

然后输出将是:

[[ 1  3  4]
 [ 5  5  6]
 [ 7  8 10]]

示例 2:将元素四舍五入到指定的小数位数

import numpy as np

# create an array
array1 = np.array([1.23456789, 2.3456789, 3.456789])

# round the elements to 2 decimal places rounded_array = np.around(array1, decimals=2)
print(rounded_array)

输出

[1.23 2.35 3.46]

np.around() 函数中的 decimal 参数指定了 array1 中的每个元素都四舍五入到小数点后2位。


示例 3:使用 out 将结果存储在指定位置

import numpy as np

# create an array 
array1 = np.array([1.2, 2.7, 3.5])

# create an empty array with the same shape as array1
rounded_array = np.zeros_like(array1)

# round the elements of array1 and store the result in rounded_array np.around(array1, out=rounded_array)
print(rounded_array)

输出

[1. 3. 4.]

在这里,在指定 out=rounded_array 后,rounded_array 包含了 array1 中每个元素的四舍五入值。

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战