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.
Python-Numpy Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics