w3resource

NumPy: Change the data type of an array


Change Array Data Type

Write a NumPy program to change an array's data type.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Creating a NumPy array 'x' with specified data type 'int32'
x = np.array([[2, 4, 6], [6, 8, 10]], np.int32)

# Printing the array 'x'
print(x)

# Printing the data type of array 'x'
print("Data type of the array x is:", x.dtype)

# Changing the data type of array 'x' to 'float'
y = x.astype(float)

# Printing the new data type of array 'y'
print("New Type: ", y.dtype)

# Printing the modified array 'y' with the new data type
print(y)

Sample Output:

[[ 2  4  6]                                                            
 [ 6  8 10]]                                                           
Data type of the array x is: int32                                     
New Type:  float64                                                     
[[  2.   4.   6.]                                                      
 [  6.   8.  10.]]

Explanation:

In the above exercise -

x = np.array([[2, 4, 6], [6, 8, 10]], np.int32): The current line creates a two-dimensional NumPy array ‘x’ with the specified elements and data type np.int32.

print("Data type of the array x is:",x.dtype): The current line prints the data type of the ‘x’ array, which is int32.

y = x.astype(float): The current line creates a new array ‘y’ by changing the data type of ‘x’ to float. The astype() function is used for this purpose.

print("New Type: ",y.dtype): The current line prints the data type of the new ‘y’ array, which is float64 (the default float data type).

print(y): The current line prints the ‘y’ array with the same elements as ‘x’ but with the new data type float64.


For more Practice: Solve these Related Problems:

  • Convert an integer array to a float array using astype and verify the result by performing a division operation.
  • Create a function that accepts an array and a target dtype, then returns the converted array while checking element types.
  • Change an array’s data type and compare the output of type() for a single element before and after conversion.
  • Test the conversion on an array with mixed numeric values to ensure the new dtype is applied uniformly.

Go to:


PREV : Reshape Array (Keep Data)
NEXT : 3x5 Array Filled with 2s


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.