How to convert array from float to int in Numpy?

Learn how to convert NumPy arrays from float to integer data types using the astype() function with various conversion methods.

numpy convert array from float to int

How to Convert NumPy Arrays from Float to Integer Data Types

To convert data type from float to int you need to use astype Numpy function and set ‘int’ as a function parameter.

See also  Count how many zeros you have in array

The following example demonstrates converting a float array to integers using astype():

import numpy as np

float_array = np.array([1.23, 12.5, 140.55, 3.14, 5.15])
print(f"My float array is: \n{float_array}")

int_array = float_array.astype('int')
print(f"My int array: \n {int_array}")

The original float_array contains decimal values; astype(‘int’) truncates these to integers (1, 12, 140, 3, 5).

Alternative approaches include np.round() for rounding before conversion, or np.rint() to convert floats to nearest integers.

See also  How to shuffle an array in Numpy?