Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a numpy array?

I have a numpy array, something like below:

data = np.array([  1.60130719e-01,   9.93827160e-01,   3.63108206e-04]) 

and I want to round each element to two decimal places.

How can I do so?

like image 538
ajayramesh Avatar asked Oct 28 '17 20:10

ajayramesh


People also ask

What is a correct method to round decimals in NumPy?

Ceil. The ceil() function rounds off decimal to nearest upper integer.

How do you round to 2 decimal places in python?

Python's round() function requires two arguments. First is the number to be rounded. Second argument decides the number of decimal places to which it is rounded. To round the number to 2 decimals, give second argument as 2.


1 Answers

Numpy provides two identical methods to do this. Either use

np.round(data, 2) 

or

np.around(data, 2) 

as they are equivalent.

See the documentation for more information.


Examples:

>>> import numpy as np >>> a = np.array([0.015, 0.235, 0.112]) >>> np.round(a, 2) array([0.02, 0.24, 0.11]) >>> np.around(a, 2) array([0.02, 0.24, 0.11]) >>> np.round(a, 1) array([0. , 0.2, 0.1]) 
like image 126
Joe Iddon Avatar answered Sep 24 '22 11:09

Joe Iddon