astype()
β Convert Array Data TypeNumPyβs astype()
method is used to convert the data type of an existing array to another type. This is useful when you want to reduce memory usage or ensure consistency in calculations.
new_array = original_array.astype(new_dtype)
Note: astype()
always returns a new array β it doesnβt change the original array.
import numpy as np
arr = np.array([1.5, 2.3, 3.9])
new_arr = arr.astype(int)
print(new_arr)
Output:
[1 2 3]
arr = np.array([10, 20, 30])
new_arr = arr.astype(str)
print(new_arr)
Output:
['10' '20' '30']
If you try to convert a string to an integer and it contains non-numeric characters, you'll get an error:
arr = np.array(['a', 'b', 'c'])
new_arr = arr.astype(int) # β This will raise an error
astype()
?float64
β float32
)You can pass data types as Python types (int
, float
) or NumPy type strings:
'int32'
, 'int64'
'float32'
, 'float64'
'bool'
, 'str'
, 'complex'
NumPy Indexing and Slicing
β‘οΈ
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!