Introduction to NumPy and Matplotlib
Chapter 2: NumPy arrays
Initialising NumPy arrays
As mentioned, you can create a np.array
instance by passing any sequence type (list
or tuples
) to constructor of np.array()
.
In NumPy, a dimension is called an axis (plural: axes).
np.array([1, 2, 3])
below has one axis (axis 0) with 3 elements.
>>> a = np.array([1, 2, 3])
>>> print(a) # A vector (3 elements)
[1 2 3]
You can create higher dimensional matrices by passing in a nested list
.
np.array([[1, 2, 3]])
below has two axes. Axis 0 has 1 elements (rows), axis 1 has 3 elements (columns). Compare this to the one above - note the difference!
>>> b = np.array([[1, 2, 3]])
>>> print(b) # 2D matrix (1x3)
[[1 2 3]]
np.array([[1, 2, 3], [4, 5, 6]])
also has two axes. Axis 0 has 2 elements (rows), axis 1 has 3 elements (columns).
>>> c = np.array([[1, 2, 3], [4, 5, 6]])
>>> print(c) # 2D matrix (2x3)
[[1 2 3]
[4 5 6]]
In higher dimensions, it is easier to think of the arrays as arrays inside arrays. The outermost list will be the first axis, the inner list will be the second, the inner-inner list will be the third, etc.
np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
has three axes. Axis 0 has 2 elements (rows), axis 1 has 2 elements (columns), axis 2 has 3 elements (depth).
>>> d = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
>>> print(d) # 3D matrix (2x2x3)
[[[ 1 2 3]
[ 4 5 6]]
[[ 7 8 9]
[10 11 12]]]