Ultimate tutorial on how to round in Numpy

I’ve prepared ultimate tutorial on how to round in Numpy.
Numpy how to round in Python

Let’s start from something basic.

How to round the basic way in Numpy?

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

rounded_array = np.round(my_array)
print(f'The rounded array: \n {rounded_array}')

How to remove decimals?

Numpy trunc function will remove everything and keep only integers.

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

trunc_round_array = np.trunc(my_array)
print(f'The trunc rounded array: \n {trunc_round_array}')

How to round down in Numpy?

Use floor Numpy function for that purpose.

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

floor_round_array = np.floor(my_array)
print(f'The floor rounded array: \n {floor_round_array}')

How to round up in Numpy?

Ceil Numpy function is rounding up.

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

ceil_round_array = np.ceil(my_array)
print(f'The ceil rounded array: \n {ceil_round_array}')

How to round to the defined decimal places?

You need define decimals parameter of round function. By default decimals = 0.

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

decimal_round_array = np.round(my_array, decimals=2)
print(f'The rounded array with 2 decimal placess: \n {decimal_round_array}')

How to round to the nearest integer?

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

rint_round_array = np.rint(my_array)
print(f'The rounded array to the nearest integer: \n {rint_round_array}')

How to round to the nearest integer towards zero?

import numpy as np
my_array = np.array([1.66, 2.44, 3.378, -5.43, 6.511113, -7.653])
print(f'The original array: \n {my_array}')

fix_round_array = np.fix(my_array)
print(f'The rounded array to the nearest integer towards zero: \n {fix_round_array}')

See also  How to mask array in Numpy?