Let’s learn how to cast an array from one dtype to another using the Numpy astype function.
Using an astype function
There is an astype Numpy method which allows us to cast from one dtype to another.
This is the sample code showing how to convert an int array to a float data type.
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}")
As you may notice, the data type changed from integer32 to float64. This is because the astype function has been used in the Python script with np.float_ as a parameter.
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.