【Python之numpy库】12.np.round() 对数组/一堆数保留n位小数

如果解决了你的问题,点个赞再走嘛٩(๑❛ᴗ❛๑)۶

对一堆数保留指定小数,用numpy库非常方便。如果是列表的话,列表本身没有太好的方法,但是可以用np.array(a)转化为数组再操作也是很好的方法

两种等价方法,设保留n位小数,则:a.round(n)或np.round(a,n)

import numpy as np

a = np.array([1.2347, 0.4214, 42.2374]).astype('float')
print(a)
print(a.round(2))
print(np.round(a, 2))

结果:

[ 1.2347  0.4214 42.2374]
[ 1.23  0.42 42.24]
[ 1.23  0.42 42.24]

猜你喜欢

转载自blog.csdn.net/m0_53392188/article/details/119742913