Round elements in Numpy matrix

In this article, we have explained how to round elements in a Numpy matrix and also, round elements to an integer with complete Python code examples.

Table of contents:

  1. Round elements in Numpy matrix
  2. Conclusion

Round elements in Numpy matrix

Round elements in Numpy matrix

The code snippet is as follows:

new_matrix = np.round(matrix, precision)

where precision is a scalar value which defines the number of digits after decimal point we want in our output.

The complete Python code example is as follows:

import numpy as np
matrix = np.array([[1.94353, 2.13254, 3.00845], [4.3423, 5.5675, 6.01029]])
print ("Original matrix = ")
print (matrix)

precision_in_output = 1
new_matrix = np.round(matrix, precision_in_output)
print ("Rounded Matrix = ")
print (new_matrix)

Output:

Original matrix = 
[[1.94353 2.13254 3.00845]
 [4.3423  5.5675  6.01029]]

Rounded Matrix = 
[[1.9 2.1 3. ]
 [4.3 5.6 6. ]]

Note: The output elements have one digit after the decimal point (if not equal to 0). This is because we have set the precision to 1.

To round the elements to an integer, we can set the precision to 0. The code snippet is as follows:

new_matrix = np.round(matrix, 0)

The complete Python code example is as follows:

import numpy as np
matrix = np.array([[1.94353, 2.13254, 3.00845], [4.3423, 5.5675, 6.01029]])
print ("Original matrix = ")
print (matrix)

precision_in_output = 0
new_matrix = np.round(matrix, precision_in_output)
print ("Rounded Matrix = ")
print (new_matrix)

Output:

Output:

Original matrix = 
[[1.94353 2.13254 3.00845]
 [4.3423  5.5675  6.01029]]

Rounded Matrix = 
[[2. 2. 3.]
 [4. 6. 6.]]

Note: The output are integer values.

Conclusion

The approach presented in much better than traversing all elements in a Numpy matrix and rounding each elements separately.