How to convert data types of arrays using NumPy in Python

In Python, an array is used to store multiple items of the same type. All the elements of an array must be of the same type. Arrays are handled by a module called Numpy.

The data types in Numpy and their respective type codes include:

  • integer (int)
  • float (f)
  • string (str)
  • boolean (bool)
  • unsigned integers (u)
  • timedelta (m)
  • datetime (M)
  • object (O)
  • Unicode (U)

We can easily specify what type of data array we want with type codes.

Code example

from numpy import array
# crreating the bool datatype of an array
my_array = array([1, 2, 3, 4, 5], dtype = 'f')
print(my_array)
print(my_array.dtype)

Code explanation

  • We import array from the numpy library.
  • We use the array() method to create an array. Then, we instruct the array to create a float data type, with the f to parameter dtype. We assign this to a variable we call my_array.
  • We print the my_array variable.
  • We use the dtype property to check for the data type.

How to convert data types for existing arrays

We make a copy of the array and use the array.astype() method to change its data type. After doing this, we can easily specify the new data type of the array we want.

Syntax

array.astype(typcode)

Parameters

The astype() method takes the typecode value as its only parameter value.

Code example

Let’s convert a float type of an array to an integer(i) type.

from numpy import array
# creating a float type of array
my_array = array([3.1, 2.1, 1.5])
# converting the old array to an integer type
new_array = my_array.astype('i')
print(new_array)
# to check the data type of array we created
print(new_array.dtype)

Code explanation

  • Line 1: We import array from the numpy module.

  • Line 4: We use the array() method to create a float type of the array and assign it to a variable called my_array.

  • Line 7: We use the astype() method to change the my_array array from a float type to an integer type and assign the value to a new variable called new_array.

  • Line 9: We print the new variable, new_array.

  • Line 12: We check for the data type of the new array, new_array, which we created with the dtype method.

Note: We can convert a type of array to another type by using the astype() method and passing the typecode of the new array type that we want as the parameter value.