如何将NumPy数组的元素四舍五入到最接近的整数
在这篇文章中,让我们讨论如何将NumPy数组中的元素四舍五入到最接近的整数。Python的numpy.rint()函数,可以将数组中的元素转换成最接近的整数。
语法: numpy.rint(x, /, out=None, *, where=True, casting='same_kind', order='K', dtype=None, subok=True[, signature, extobj] ) =<ufunc ‘rint’>
示例 1:
import numpy as n
# create array
y = n.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7])
print("Original array:", end=" ")
print(y)
# round to nearest integer
y = n.rint(y)
print("After rounding off:", end=" ")
print(y)
输出:
示例 2:
import numpy as n
# create array
y = n.array([-0.2, 0.7, -1.4, -4.5, -7.6, -19.7])
print("Original array:", end=" ")
print(y)
# round to nearest integer
y = n.rint(y)
print("After rounding off:", end=" ")
print(y)
输出: