Source From Here
HowToWe 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.
Example1
- # 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)
Let's see how to change the data type of a numpy array from float64 to &int32.
Example2
- 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}: {array}')
- # 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}: {array}')
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
沒有留言:
張貼留言