How to round all the elements of a matrix with numpy in python ?

September 21, 2021    /    Viewed: 231    /    Comments: 0    /    Edit


Examples of how to round all the elements of a matrix with numpy in python:

Create a matrix of float with numpy

Let's create first a matrix of float with numpy

import numpy as np

data = np.random.rand(4,5) * 100.0

gives for example

array([[ 0.54545428, 62.89794368, 50.60548232, 57.47598712, 11.78324876],
       [57.10987983, 19.58684319,  7.67338724, 10.76866391, 90.78997325],
       [62.25706073, 42.60884215, 58.72412611, 91.84459902, 26.1276944 ],
       [ 6.51345784, 76.53505447, 71.20775378, 56.07274006, 79.39644899]])

Round all elements of a matrix with numpy

To round all elements of a matrix with numpy, a solution is to use numpy.matrix.round, example round with 2 decimals:

np.round(data,2)

gives

array([[ 0.55, 62.9 , 50.61, 57.48, 11.78],
       [57.11, 19.59,  7.67, 10.77, 90.79],
       [62.26, 42.61, 58.72, 91.84, 26.13],
       [ 6.51, 76.54, 71.21, 56.07, 79.4 ]])

example round with 1 decimals:

np.round(data,1)

gives

array([[ 0.5, 62.9, 50.6, 57.5, 11.8],
       [57.1, 19.6,  7.7, 10.8, 90.8],
       [62.3, 42.6, 58.7, 91.8, 26.1],
       [ 6.5, 76.5, 71.2, 56.1, 79.4]])

example round with 0 decimals:

np.round(data,0)

gives

array([[ 1., 63., 51., 57., 12.],
       [57., 20.,  8., 11., 91.],
       [62., 43., 59., 92., 26.],
       [ 7., 77., 71., 56., 79.]])

Convert a matrix of floats into integers

Another solution is to convert the matrix of floats to integers with astype(int):

data.astype(int)

gives

array([[ 0, 62, 50, 57, 11],
       [57, 19,  7, 10, 90],
       [62, 42, 58, 91, 26],
       [ 6, 76, 71, 56, 79]])

References


Card image cap
profile-image
Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!