+2 votes
in Programming Languages by (74.9k points)
What function should I use to round each element of a Numpy array to the given number of decimals?

1 Answer

+1 vote
by (353k points)
selected by
 
Best answer

Numpy's round() function can be used to round each element of a Numpy array.

Here is an example:

>>> import numpy as np
>>> gg=np.array([[5.6,8.3,1.8],[2.11,8.32,3.56],[0.98,5.12,0.45]])
>>> gg
array([[5.6 , 8.3 , 1.8 ],
       [2.11, 8.32, 3.56],
       [0.98, 5.12, 0.45]])
>>> gg.round()
array([[6., 8., 2.],
       [2., 8., 4.],
       [1., 5., 0.]])
>>> np.round(gg,1)
array([[5.6, 8.3, 1.8],
       [2.1, 8.3, 3.6],
       [1. , 5.1, 0.4]])
>>> np.round(gg,2)
array([[5.6 , 8.3 , 1.8 ],
       [2.11, 8.32, 3.56],
       [0.98, 5.12, 0.45]])


...