Python’s library for data science, NumPy, allows you to slice multidimensional arrays easily.
For multi-dimensional slices, you can use one-dimensional slicing for each axis separately. You define the slices for each axis, separated by a comma.
Here are a few examples drawn from my comprehensive NumPy tutorial. Take your time to thoroughly understand each of them.
import numpy as np a = np.arange(16) a = a.reshape((4,4)) print(a) # [ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11] # [12 13 14 15]] print(a[:, 1]) # Second column: # [ 1 5 9 13] print(a[1, :]) # Second row: # [4 5 6 7] print(a[1, ::2]) # Second row, every other element # [4 6] print(a[:, :-1]) # All columns except last one # [[ 0 1 2] # [ 4 5 6] # [ 8 9 10] # [12 13 14]] print(a[:-1]) # Same as a[:-1, :] # [[ 0 1 2 3] # [ 4 5 6 7] # [ 8 9 10 11]]
As you can see in the above examples, slicing multi-dimensional NumPy arrays is easy β if you know NumPy arrays and how to slice them. The most important information to remember is that you can slice each axis separately. If you donβt specify the slice notation for a specific axis, the interpreter applies the default slicing (i.e., the colon :
).
I will skip a detailed explanation of the NumPy dot notation ...
– just note that you can βfill inβ the remaining default slicing colons by using three dots. Here is an example:
import numpy as np a = np.arange(3**3) a = a.reshape((3,3,3)) print(a) ##[[[ 0 1 2] ## [ 3 4 5] ## [ 6 7 8]] ## ## [[ 9 10 11] ## [12 13 14] ## [15 16 17]] ## ## [[18 19 20] ## [21 22 23] ## [24 25 26]]] print(a[0, ..., 0]) # Select the first element of axis 0 # and the first element of axis 2. Keep the rest. # [0 3 6] # Equal to a[0, :, 0]
Where to go from here?
Today, data science is at the heart of every professional coder’s core knowledge. You simply cannot afford NOT to know about data science.
However, many people find data science complex to understand and boring to learn, study, and ultimately master.
That’s why I have written a puzzle-based NumPy textbook that’s easily understandable, even for beginners, and a lot of fun to work through. You just solve the NumPy puzzles given in the book and become a NumPy master in a step-by-step manner.