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

This tutorial will focus on How to convert a float array to int in Python. We 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.

Convert 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]

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]

let us know if you know any other way to achieve our goal in the below comment section. Hope you enjoyed this NumPy array tutorial.

Also learn,

Leave a Reply

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