Coding Ref

How to use numpy.round() in Python

How to use numpy.round() in Python

numpy.round() is a function in the NumPy library in Python that is used to round the elements of an array to the nearest integer.

Syntax

The syntax for the numpy.round() function is as follows:

numpy.round(a, decimals=0, out=None)
  • a is the input array.
  • decimals specifies the number of decimal places to which the elements of the array should be rounded.
  • out is optional and is used to specify the output array.

The function returns an array with the rounded elements of the input array.

Examples

Here are a few examples of how to use the numpy.round() function in Python:

Example 1: Round the numbers in the array to the nearest integer

main.py
import numpy as np

# Round the numbers in the array to the nearest integer
a = np.array([1.5, 2.3, 3.7, 4.1, 5.9])
b = np.round(a)
print(b)
output
[2. 2. 4. 4. 6.]

Example 2: Round the numbers in the array to the nearest integer and store the result in the same array

main.py
import numpy as np

a = np.array([1.5, 2.3, 3.7, 4.1, 5.9])
np.round(a, out=a)
print(a)
output
[2. 2. 4. 4. 6.]

Example 3: Round the numbers in the array to two decimal places

main.py
import numpy as np

a = np.array([1.532, 2.387, 3.714, 4.112, 5.998])
b = np.round(a, decimals=2)
print(b)
output
[1.53, 2.39, 3.71, 4.11, 6.  ])

You'll also like

Related tutorials curated for you

    How to use numpy.percentile() in Python

    ModuleNotFoundError: No module named 'numpy' in Python

    How to use numpy.exp() in Python

    NumPy: np.arrange()

    How to use numpy.random.uniform() in Python

    What does numpy.arrange() do?

    How to use numpy.round() in Python

    How to use numpy.vstack() in Python

    How to use numpy.ravel() in Python

    NumPy numpy.transpose()

    How to use numpy.ndarray.flatten() in Python

    How to use numpy.clip() in Python