如何使用 NumPy 将数组元素舍入到给定的小数位数?
在 NumPy 中,我们可以借助 round() 将数组元素四舍五入到给定的小数位数。
句法:
np.round(a, decimals=0, out=None)
第一个参数是一个数组,第二个参数是需要四舍五入的小数位数。如果没有参数将作为第二个参数传递,那么默认情况下它采用 0。它将返回圆形数组元素到给定的小数位数。
示例 1:
Python3
import numpy as np
# perform the numpy.round
rounded_array = np.round([1.5, 1.53, 1.23, 3.89])
# print the rounded_array
print(rounded_array)
Python3
import numpy as np
# perform the numpy.round
rounded_array = np.round([1.5, 1.53, 1.23, 3.89],
decimals=1)
# print the rounded_array
print(rounded_array)
Python3
import numpy as np
# perform the numpy.round
rounded_array = np.round(
[1.534, 1.5389, 1.2301, 3.89903, 6.987, 4.09], decimals=2)
# print the rounded_array
print(rounded_array)
输出
[2. 2. 1. 4.]
示例 2:
Python3
import numpy as np
# perform the numpy.round
rounded_array = np.round([1.5, 1.53, 1.23, 3.89],
decimals=1)
# print the rounded_array
print(rounded_array)
输出:
[1.5 1.5 1.2 3.9]
例子
Python3
import numpy as np
# perform the numpy.round
rounded_array = np.round(
[1.534, 1.5389, 1.2301, 3.89903, 6.987, 4.09], decimals=2)
# print the rounded_array
print(rounded_array)
输出:
[1.53 1.54 1.23 3.9 6.99 4.09]