NumPy ndarray.dtype

The dtype attribute of a NumPy ndarray object returns the data type of the array’s elements. It provides information about the type of data stored in the array, such as integers, floats, or custom-defined types.

Syntax

</>
Copy
ndarray.dtype

Return Value

Returns a numpy.dtype object, which describes the type of data stored in the array. It includes information about the data type, byte order, and size.


Examples

1. Checking the Data Type of an Array

In this example, we create an integer array and check its data type using the dtype attribute.

</>
Copy
import numpy as np

# Creating a NumPy array with integer values
arr = np.array([1, 2, 3, 4, 5])

# Checking the data type of the array elements
print(arr.dtype)  # Output: int64 (or int32 depending on the system)

Output:

int64

The output shows that the array elements are stored as 64-bit integers.

2. Checking the Data Type of a Floating-Point Array

Here, we create a floating-point array and check its data type.

</>
Copy
import numpy as np

# Creating a NumPy array with floating-point values
arr = np.array([1.5, 2.7, 3.8, 4.2])

# Checking the data type of the array elements
print(arr.dtype)  # Output: float64

Output:

float64

Since the elements are decimal numbers, NumPy assigns them the float64 data type by default.

3. Creating an Array with a Specific Data Type

We can explicitly specify the data type of a NumPy array using the dtype parameter.

</>
Copy
import numpy as np

# Creating an array with integers but specifying dtype as float
arr = np.array([1, 2, 3, 4], dtype=np.float32)

# Checking the data type
print(arr.dtype)  # Output: float32

Output:

float32

Even though the values are integers, they are stored as 32-bit floating-point numbers due to the specified dtype.

4. Checking Data Type of a Boolean Array

Boolean arrays store elements as bool type.

</>
Copy
import numpy as np

# Creating a boolean NumPy array
arr = np.array([True, False, True])

# Checking the data type
print(arr.dtype)  # Output: bool

Output:

bool

Since the array contains boolean values, NumPy assigns them the bool data type.

5. Checking Data Type of a String Array

NumPy stores string data using the U (Unicode) type with a fixed length.

</>
Copy
import numpy as np

# Creating a NumPy array with string elements
arr = np.array(["apple", "banana", "cherry"])

# Checking the data type
print(arr.dtype)  # Output: <U6 (or similar based on longest string length)

Output:

<U6

The <U6 output means that the array elements are Unicode strings with a maximum length of 6 characters.