The most effective way to change the data type of an existing array is to create a copy using the astype() method.
The astype() function generates a copy of the array and allows you to specify the desired data type as a parameter.
You can specify the data type using a string, such as ‘f’ for float or ‘i’ for integer, or by using the data type directly, such as float for float and int for integer.
Change the data type from float to integer by using ‘i’ as the parameter value.
import numpy as np arr = np.array([1.1, 2.1, 3.1]) newarr = arr.astype(‘i’) print(newarr) print(newarr.dtype) |
Change the data type from float to integer by using int as the parameter value.
import numpy as np arr = np.array([1.1, 2.1, 3.1]) newarr = arr.astype(int) print(newarr) print(newarr.dtype) |
Change the data type from integer to boolean.
import numpy as np arr = np.array([1, 0, 3]) newarr = arr.astype(bool) print(newarr) print(newarr.dtype) |