Change data type of given numpy array

In this post, we are going to see the ways in which we can change the dtype of the given numpy array. In order to change the dtype of the given array object, we will use numpy.astype() function. The function takes an argument which is the target data type. The function supports all the generic types and built-in types of data.

Problem #1 : Given a numpy array whose underlying data is of 'int32' type. Change the dtype of the given object to 'float64'.

Solution : We will use numpy.astype() function to change the data type of the underlying data of the given numpy array.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
  
# Print the array
print(arr)

chevron_right


Output :

Now we will check the dtype of the given array object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Print the dtype
print(arr.dtype)

chevron_right


Output :

As we can see in the output, the current dtype of the given array object is ‘int32’. Now we will change this to ‘float64’ type.

filter_none

edit
close

play_arrow

link
brightness_4
code

# change the dtype to 'float64'
arr = arr.astype('float64')
  
# Print the array after changing
# the data type
print(arr)
  
# Also print the data type
print(arr.dtype)

chevron_right


Output :

Problem #2 : Given a numpy array whose underlying data is of 'int32' type. Change the dtype of the given object to 'complex128'.

Solution : We will use numpy.astype() function to change the data type of the underlying data of the given numpy array.

filter_none

edit
close

play_arrow

link
brightness_4
code

# importing the numpy library as np
import numpy as np
  
# Create a numpy array
arr = np.array([10, 20, 30, 40, 50])
  
# Print the array
print(arr)

chevron_right


Output :

Now we will check the dtype of the given array object.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Print the dtype
print(arr.dtype)

chevron_right


Output :

As we can see in the output, the current dtype of the given array object is ‘int32’. Now we will change this to ‘complex128’ type.

filter_none

edit
close

play_arrow

link
brightness_4
code

# change the dtype to 'complex128'
arr = arr = arr.astype('complex128')
  
# Print the array after changing
# the data type
print(arr)
  
# Also print the data type
print(arr.dtype)

chevron_right


Output :



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.