Change Datatype of a NumPy array in Python
Have you wondered What if we used the wrong datatype in NumPy array or you want to modify it later for some reason?
The simplest answer to the above question is A big Yes!
So today in this tutorial, we will learn how to change the datatype of a NumPy array in Python.
About astype() function
astype() is a built-in function in Python to convert the data type of an existing array into another data type. It converts the type of an array into the target datatype. Let’s move to the example for a better understanding of the given topic.
Steps to follow:
- Import NumPy as np.
- Make an array of integer values.
- Use astype() function to convert it into float.
- Use astype() function to convert it into complex.
import numpy as np arr=np.array([1,2,3,4,5]) print(arr.dtype)
We have created an array of integer values and also we have checked its data type using type. The output of the above code results int32.
Now let’s change the data type of the array we have just made using astype() function.
First, let’s convert it into data type float and then print the array and its datatype as:
arr=arr.astype('float64') print(arr) print(arr.dtype)
This code will print the entire array and data type as the float. So, let’s have a look at the output.
OUTPUT: [1. 2. 3. 4. 5.] float64
As for now, we have successfully converted an integer array into float. Our next task is to convert it into complex data type.
Let’s move to the snippet part:
arr=arr.astype(complex) print(arr) print(arr.dtype)
Output for the above code is: [1.+0.j 2.+0.j 3.+0.j 4.+0.j 5.+0.j] complex128
As you can see in the output, we have accomplished the task to convert integer array into different data types using astype() function. We can also convert it into other data types of our choice.
Thanks for reading! Feel free to comment and share your reviews on this article.