How to convert a float array to int in Python – NumPy

Learn how to convert float array to int in PythonWe will learn how to change the data type of an array from float to integer.

In my previous tutorial, I have shown you How to create 2D array from list of lists in Python.

I will also show you how you can round it off to the nearest integer value.

Convert NumPy float array to int in Python

Here we have used NumPy Library.

We can convert in different ways:

  • using dtype=’int’
  • using astype(‘int’)
  • np.int_(array)

Let’s understand this with an easy example step by step.

At first, we need a list having float elements in it.

codespeedy_float_list = [45.45,84.75,69.12]

Now let’s convert this list from float to int.

array_int = np.array(codespeedy_float_list, dtype='int')

Program to convert float array to int:

import numpy as np
codespeedy_float_list = [45.45,84.75,69.12]
array_int = np.array(codespeedy_float_list, dtype='int')
print(array_int)

Output:

$ python codespeedy.py
[45 84 69]

Round off the floating numbers in a NumPy array to the nearest integer values

import numpy as np

codespeedy_float_list = [45.45, 84.75, 69.12]
rounded_int_list = [int(round(x)) for x in codespeedy_float_list]
array_int = np.array(rounded_int_list, dtype='int')
print(array_int)

Output:

[45 85 69]

Convert using astype(‘int’)

Let’s achieve our goal with a different technique.

import numpy as np
codespeedy_float_list = [45.45,84.75,69.12]
codespeedy_array = np.array(codespeedy_float_list)
print(codespeedy_array.astype('int'))

Output:

$ python codespeedy.py
[45 84 69]

Convert float to int array using np.int_

Here we have another way;

import numpy as np
codespeedy_float_list = [45.45,84.75,69.12]
codespeedy_array = np.array(codespeedy_float_list)
print(np.int_(codespeedy_array))

Output:

$ python codespeedy.py
[45 84 69]

Also, learn,

Leave a Reply

Your email address will not be published. Required fields are marked *