NumPy round()

round() 函数将数组的浮点元素四舍五入到最近的整数,或四舍五入到指定的小数位数。

示例

import numpy as np

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

# use round() to round the elements of the array to the nearest integer rounded_array = np.round(array1)
# print the rounded array print(rounded_array) # Output : [1. 3. 4. 4. 6.]

round() 语法

round() 的语法是:

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

round() 参数

round() 函数接受一个参数:

  • array - 需要进行四舍五入的输入数组
  • decimal (可选) - array 的元素要四舍五入到的小数位数
  • out (可选) - 结果将存储在其上的输出数组。

round() 返回值

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


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

import numpy as np

# create a 2-D array
array1 = np.array([[1.2, 2.7, 3.5],
                                [4.1, 5.9, 6.4]])

# use round() to round the elements of the array to the nearest integer rounded_array = np.round(array1)
print(rounded_array)

输出

[[1. 3. 4.]
 [4. 6. 6.]]

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

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

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

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

然后输出将是:

[[1 3 4]
 [4 6 6]]

示例 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.round(array1, decimals=2)

print(rounded_array)

输出

[1.23 2.35 3.46]

array1 中的每个元素都四舍五入到小数点后 **2** 位,如 np.round() 函数中的 decimals 参数指定的那样。


示例 3:在 round() 中使用 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.round(array1, out=rounded_array)
print(rounded_array)

输出

[1. 3. 4.]

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

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

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

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