Today we’ll be talking about numpy array dimensions.
Vectors – 1-Dimensional Arrays
In numpy we can create multidimensional arrays. The arrays we’ve been creating so far are all 1-dimensional. You can check out numpy array dimensions using the ndim method:
>>> a = np.array([1, 2, 3])
>>> print(a)
[1 2 3]
>>> np.ndim(a)
1
1- dimensional arrays are called vectors. They contain all elements of the same type. You can check the type of the elements of an array using the dtype attribute:
>>> print(a.dtype)
int32
Scalars – 0-Dimensional Arrays
If we use scalars, which are just integer or float values, numpy treats them as 0-dimensional arrays. Have a look:
>>> b = np.array(5)
>>> c = np.array(3.8)
>>> print(b)
5
>>> print(c)
3.8
>>> np.ndim(b)
0
>>> np.ndim(c)
0
Multidimensional Arrays
We can also create arrays of more than 1 dimension. This can be done by passing nested lists or tuples to the array method. There is theoretically no limit as to the maximum number of numpy array dimensions, but you should keep it reasonably low or otherwise you will soon lose track of what’s going on or at least you will be unable to handle such complex arrays anymore.
Here’s an example of a 2-dimensional array:
>>> a = [[1, 2, 3], [5, 6, 7], [8, 9, 10]]
>>> A = np.array(a)
>>> print(A)
[[ 1 2 3]
[ 5 6 7]
[ 8 9 10]]
>>> A.ndim
2
And here’s an example of a 3-dimensional array:
>>> b = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[9, 10], [11, 12]]]
>>> B = np.array(b)
>>> print(B)
[[[ 1 2]
[ 3 4]]
[[ 5 6]
[ 7 8]]
[[ 9 10]
[11 12]]]
>>> B.ndim
3
By the way, instead of using the ndim method of numpy, we can use the ndim attribute directly on the numpy array:
>>> np.ndim(B)
3
>>> B.ndim
3
Here you can watch the video version: