NumPy: Get the dimensions, shape, and size of an array | note.nkmk.me (original) (raw)
You can get the number of dimensions, the shape (length of each dimension), and the 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.
Contents
- Number of dimensions of a NumPy array: ndim
- Shape of a NumPy array: shape
- Size of a NumPy array: size
- Size of the first dimension of a NumPy array: len()
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 using the ndim
attribute.
`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
The shape of a NumPy array, i.e., the length of each dimension, is represented as a tuple and can be accessed using the shape
attribute.
For a one-dimensional array, shape
is still represented as a one-element tuple rather than a single integer. Note that a tuple with a single element must include 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.
`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 a built-in Python 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
`