How to convert float array to int in Python?

Ways to convert float array to int in Python

We can use the numpy.asarray() function to convert float array to int in Python. It accepts an input object and returns a numpy array. This input can be a list, tuple, or array. We can use the dtype parameter to set the type of the array.

To convert float array to int in Python:

  1. Create a float array in Python.

  2. Use asarray() function to convert float array to int in Python.

import numpy as np
# Convert float array to int in Python
float_arr = np.array([3.55,6.3,4.2])
# Use the asarray() function
int_arr = np.asarray(float_arr, dtype = int)
print(int_arr)
# Output: [3 6 4]        

In the above sample code, we convert the float_arr array to an int array using the asarray() function.

Similarly, we can use the numpy.astype() function which creates a copy of the array by type-casting its elements to the required type.

To convert float array to int in Python:

  1. Create a float array in Python.

  2. Use astype() function to convert float array to int in Python.

import numpy as np
# Convert float array to int in Python
float_arr = np.array([3.55,6.3,4.2])
# Use the astype() function
int_arr = float_arr.astype(int)
print(int_arr)
# Output: [3 6 4]        

The numpy.int_ is the scalar datatype to represent integers in arrays. The constructor of this type can also convert float array to int in Python.

To convert float array to int in Python:

  1. Create a float array in Python.

  2. Use int_() constructor to convert float array to int in Python.

import numpy as np
# Convert float array to int in Python
float_arr = np.array([3.55,6.3,4.2])
# Use the int_() constructor
int_arr = np.int_(float_arr)
print(int_arr)
# Output: [3 6 4]        

To conclude

This particular tutorial demonstrates different methods to convert float array to int in Python. The first method demonstrates the use of the numpy.asarray() function. The following method creates a copy of the array as an int using the numpy.astype() function. The final method demonstrates the use of the numpy.int_ constructor.

Explore more from this category at Python NumPy Arrays. Alternatively, search and view other topics at All Tutorials.