NumPy: Get the number of dimensions, shape, and size of ndarray
You can get the number of dimensions, shape (length of each dimension), and size (total number of elements) of a NumPy array (numpy.ndarray
) using the ndim
, shape
, and size
attributes. The built-in len()
function returns the size of the first dimension.
Use the following one- to three-dimensional arrays as examples.
import numpy as np
a_1d = np.arange(3)
print(a_1d)
# [0 1 2]
a_2d = np.arange(12).reshape((3, 4))
print(a_2d)
# [[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
a_3d = np.arange(24).reshape((2, 3, 4))
print(a_3d)
# [[[ 0 1 2 3]
# [ 4 5 6 7]
# [ 8 9 10 11]]
#
# [[12 13 14 15]
# [16 17 18 19]
# [20 21 22 23]]]
Number of dimensions of a NumPy array: ndim
You can get the number of dimensions of a NumPy array as an integer value with the ndim
attribute of numpy.ndarray
.
print(a_1d.ndim)
# 1
print(type(a_1d.ndim))
# <class 'int'>
print(a_2d.ndim)
# 2
print(a_3d.ndim)
# 3
To add a new dimension, use numpy.newaxis
or numpy.expand_dims()
. See the following article for details.
Shape of a NumPy array: shape
You can get the shape, i.e., the length of each dimension, of a NumPy array as a tuple with the shape
attribute of numpy.ndarray
.
For a one-dimensional array, shape
is still represented as a tuple with one element rather than an integer value. Note that a tuple with a single element has a trailing comma.
print(a_1d.shape)
# (3,)
print(type(a_1d.shape))
# <class 'tuple'>
print(a_2d.shape)
# (3, 4)
print(a_3d.shape)
# (2, 3, 4)
For example, in the case of a two-dimensional array, shape
represents (number of rows, number of columns)
. If you want to access either the number of rows or columns, you can retrieve each element of the tuple individually.
print(a_2d.shape[0])
# 3
print(a_2d.shape[1])
# 4
You can also unpack the tuple and assign its elements to different variables.
row, col = a_2d.shape
print(row)
# 3
print(col)
# 4
Use reshape()
to convert the shape. See the following article for details.
Size of a NumPy array: size
You can get the size, i.e., the total number of elements, of a NumPy array with the size
attribute of numpy.ndarray
.
print(a_1d.size)
# 3
print(type(a_1d.size))
# <class 'int'>
print(a_2d.size)
# 12
print(a_3d.size)
# 24
Size of the first dimension of a NumPy array: len()
len()
is the Python built-in function that returns the number of elements in a list or the number of characters in a string.
For a numpy.ndarray
, len()
returns the size of the first dimension, which is equivalent to shape[0]
. It is also equal to size
only for one-dimensional arrays.
print(len(a_1d))
# 3
print(a_1d.shape[0])
# 3
print(a_1d.size)
# 3
print(len(a_2d))
# 3
print(a_2d.shape[0])
# 3
print(len(a_3d))
# 2
print(a_3d.shape[0])
# 2