How to cast an array from one dtype to another using Numpy astype?

Let’s learn how to cast an array from one dtype to another using the Numpy astype function.
Numpy astype int to float

Using an astype function

The astype method in NumPy allows us to cast an array from one dtype to another.

In addition to casting an array from one data type to another, you can also cast an array to a specific data type. To do this, you can use the astype function with the dtype parameter. The dtype parameter specifies the data type that you want to cast the array to.

See also  Ways how to convert numpy array to string

For example, the following code will cast the array my_int_array to the data type np.float64:

import numpy as np

my_int_array = np.array([1, 2, 4, 7, 17, 43, 4, 9])
print(f"My int array: \n {my_int_array}")
print(f"dtype is: {my_int_array.dtype}")

my_float_array = my_int_array.astype(np.float_)
print(f"My float array: \n {my_float_array}")
print(f"dtype is: {my_float_array.dtype}")

Numpy astype int to float

As you may notice, the data type changed from an integer type to float, which is represented by float_ in this example. This is because the astype function has been used in the Python script with np.float_ as a parameter.

See also  How to Append to an Empty Array in Numpy (with Examples)

In the same way, you can convert other data types. Just remember that it may change your values. Converting from int to float in my example added decimals to the values. Casting from float to int would truncate decimals.