Every NumPy array has a data type (called dtype) that tells us what kind of elements are stored in the array β for example, integers, floats, or strings.
int32, int64 β Integer numbersfloat32, float64 β Floating point numbersbool_ β Boolean values (True or False)complex64, complex128 β Complex numbersstr_ or unicode_ β StringsUse array.dtype to check the data type of a NumPy array:
import numpy as np
arr = np.array([10, 20, 30])
print(arr.dtype)
Output:
int64
dtypeYou can specify the data type when creating an array:
# Create float array
arr = np.array([1, 2, 3], dtype='float32')
print(arr)
Output:
[1. 2. 3.]
Use astype() to convert an arrayβs data type.
arr = np.array([1.7, 2.8, 3.9])
int_arr = arr.astype('int')
print(int_arr)
Output:
[1 2 3]
astype() creates a new array β it doesnβt modify the original array.
dtype Important?Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!