How to view the dimensions, size, shape, and data type of a NumPy array in Python

Published on Aug. 22, 2023, 12:16 p.m.

To view the dimensions, size, shape, and data type of a NumPy array in Python, you can use various attributes of the array object. Here are some examples:

import numpy as np

# create a NumPy array
arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# view the number of dimensions
print(f'Number of dimensions: {arr.ndim}')

# view the size (total number of elements)
print(f'Size: {arr.size}')

# view the shape (number of elements in each dimension)
print(f'Shape: {arr.shape}')

# view the data type of the array elements
print(f'Data type: {arr.dtype}')

This code creates a 2-dimensional NumPy array, and then prints out its number of dimensions, size, shape, and data type. The expected output is:

Number of dimensions: 2
Size: 9
Shape: (3, 3)
Data type: int64

Note that for more complex arrays, the output of these operations can be more involved. Additionally, using functions such as np.info() or np.array_repr() can provide additional detailed information about the array object.

Tags: