We have a method called astype(data_type) to change the data type of a numpy array. If we have a numpy array of type float64, then we can change it to int32 by giving the data type to the astype() method of numpy array.
We can check the type of numpy array using the dtype class. Let's check the data type of sample numpy array.
Example
# importing numpy library import numpy as np # creating numpy array array = np.array([1, 2, 3, 4, 5]) # printing the data type of the numpy array print(array.dtype)
Output
If you run the above code, you will get the following results.
int32
Let's see how to change the data type of a numpy array from float64 to &int32.
Example
# importing numpy library import numpy as np # creating numpy array of type float64 array = np.array([1.5, 2.6, 3.7, 4.8, 5.9]) # type of array before changing print(f'Before changing {array.dtype}') # changing the data type of numpy array using astype() method array = array.astype(np.int32) # type of array after changing print(f'\nAfter changing {array.dtype}')
Output
If you run the above program, you will get the following results.
Before changing float64 After changing int32
We can use any data type present in the numpy module or general data types of Python. You can find the list of data types present in numpy here.
Conclusion
I hope you have learned the conversion of data types for numpy array. If you are facing any problems related to the tutorial, mention them in the comment section.