pythonarraysnumpyrounding

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?


Solution

  • 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])