如何将 NumPy 数组的元素舍入到最接近的整数?
先决条件: Python NumPy
在本文中,让我们讨论如何将 NumPy 数组的元素四舍五入到最接近的整数。 Python的 numpy.rint()函数,可以将数组的元素转换为最接近的整数。
Syntax: numpy.rint(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) =
示例 1:
Python3
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)
# rount to nearest integer
y = n.rint(y)
print("After rounding off:", end=" ")
print(y)
Python3
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)
# rount to nearest integer
y = n.rint(y)
print("After rounding off:", end=" ")
print(y)
输出:
示例 2:
Python3
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)
# rount to nearest integer
y = n.rint(y)
print("After rounding off:", end=" ")
print(y)
输出: