The SciPy library provides a convenient way to round all the elements of a matrix with numpy in python. Using numpy.around will allow us to set the number of decimal places and rounding type for each element in the array. Examples

## Create a matrix of float with numpy

Let's create first a matrix of float with numpy

`import numpy as np`

`np.random.seed(42)`

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

Output

`array([[37.45401188, 95.07143064, 73.19939418, 59.86584842, 15.60186404],`

`[15.59945203, 5.80836122, 86.61761458, 60.11150117, 70.80725778],`

`[ 2.05844943, 96.99098522, 83.24426408, 21.23391107, 18.18249672],`

`[18.34045099, 30.4242243 , 52.47564316, 43.19450186, 29.12291402]])`

## Round all elements of a matrix with numpy

For example, if you wanted to round all numbers in a matrix to two decimal places, you would use np.around(matrix, decimals=2). You can also use numpy.floor or numpy.ceil to round numbers down or up respectively. Additionally, if you want to round all elements of a matrix element-wise, you can use the np.round function, which provides more control over how the rounding is performed:

`np.around(data,2)`

Output

`array([[37.45, 95.07, 73.2 , 59.87, 15.6 ],`

`[15.6 , 5.81, 86.62, 60.11, 70.81],`

`[ 2.06, 96.99, 83.24, 21.23, 18.18],`

`[18.34, 30.42, 52.48, 43.19, 29.12]])`

Example round with 1 decimals:

`np.around(data,1)`

Output

`array([[37.5, 95.1, 73.2, 59.9, 15.6],`

`[15.6, 5.8, 86.6, 60.1, 70.8],`

`[ 2.1, 97. , 83.2, 21.2, 18.2],`

`[18.3, 30.4, 52.5, 43.2, 29.1]])`

Example round with 0 decimals:

`np.around(data,0)`

Output

`array([[37., 95., 73., 60., 16.],`

`[16., 6., 87., 60., 71.],`

`[ 2., 97., 83., 21., 18.],`

`[18., 30., 52., 43., 29.]])`

## Numpy round() vs around()

Same functions

`np.round(data,2)`

Output

`array([[37.45, 95.07, 73.2 , 59.87, 15.6 ],`

`[15.6 , 5.81, 86.62, 60.11, 70.81],`

`[ 2.06, 96.99, 83.24, 21.23, 18.18],`

`[18.34, 30.42, 52.48, 43.19, 29.12]])`

## Convert a matrix of floats into integers

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

`data.astype(int)`

Output

`array([[ 0, 62, 50, 57, 11],`

`[57, 19, 7, 10, 90],`

`[62, 42, 58, 91, 26],`

`[ 6, 76, 71, 56, 79]])`

## References

Links | Site |
---|---|

numpy.random.rand | numpy.org |

round() | numpy.org |

around() | numpy.org |