NumPy around()

The around() function rounds the elements of an array to the nearest whole number.

Example

import numpy as np

# create an array with decimal values
array1 = np.array([1.234, 2.678, 3.543, 4.876, 5.192])

# round the elements using around() result = np.around(array1)
print(result) # Output : [1. 3. 4. 5. 5.]

around() Syntax

The syntax of around() is:

numpy.round(array, decimals=0, out=None)

around() Arguments

The around() function takes one argument:

  • array - the input array whose elements are to be rounded
  • decimal (optional) - number up to which the elements of array is rounded
  • out (optional) - the output array where the result will be stored.

around() Return Value

The around() function returns a new array with the rounded values.


Example 1: Round Array Elements to Nearest Integer

import numpy as np

# create a 2D array with decimal values
array1 = np.array([[1.2, 2.7, 3.5],
                                [4.8, 5.1, 6.3],
                                [7.2, 8.5, 9.9]])

# round the elements to the nearest integer using np.around() result = np.around(array1)
print("Rounded array:") print(result)

Output

Rounded array:
[[ 1.  3.  4.]
 [ 5.  5.  6.]
 [ 7.  8. 10.]]

In the above example, the np.around() function rounds the elements of the array to the nearest integer.

However, even after rounding, the data type of the array remains as float64. That is the reason for the presence of a decimal point in the output.

If you prefer to have the output as integers without the decimal points, you can convert the data type of the rounded array to int using astype() as:

rounded_array = np.around(array1).astype(int)

Then the output will be,

[[ 1  3  4]
 [ 5  5  6]
 [ 7  8 10]]

Example 2: Round Elements to Given Number of Decimal Places

import numpy as np

# create an array
array1 = np.array([1.23456789, 2.3456789, 3.456789])

# round the elements to 2 decimal places rounded_array = np.around(array1, decimals=2)
print(rounded_array)

Output

[1.23 2.35 3.46]

Each element in array1 is rounded to 2 decimal places as specified by the decimal argument in the np.around() function.


Example 3: Use out to Store the Result in Desired Location

import numpy as np

# create an array 
array1 = np.array([1.2, 2.7, 3.5])

# create an empty array with the same shape as array1
rounded_array = np.zeros_like(array1)

# round the elements of array1 and store the result in rounded_array np.around(array1, out=rounded_array)
print(rounded_array)

Output

[1. 3. 4.]

Here, after specifying out=rounded_array, the rounded_array contains the rounded values of each element in array1.