Indexing and slicing
Now, let’s talk about how to access elements in a NumPy array.
For a 1D array, you access it just like a Python list
, with a square bracket []
. Slicing works too.
x = np.array([1,2,3,4,5])
print(x[0]) ## 1
print(x[-1]) ## 5
print(x[2:4]) ## [3 4]
print(x[:3]) ## [1 2 3]
For multidimensional arrays, you access indices of different axes/dimensions by separating the indices with a comma. Slicing will also work.
y = np.array([[1, 2, 3, 5], [-1, 4, 7, 9]])
print(y[0,1]) ## 2 (row 0, col 1)
print(y[-1,-2]) ## 7 (last row, second-to-last col)
print(y[1:3, :-1]) ## [[-1 4 7]] (figure this out yourself!)
print(y[:,:]) ## What does this do?
print(y[0]) ## And this one?
While you can also use y[0][1]
as in a Python list
, this is much slower than y[0,1]
. So use y[0,1]
if you want your code to be more efficient!
Integer array indexing
You can also access arbitrary groups of items in an np.ndarray
, using a list of indices.
print(y[[1, 0], [3, 2]]) ## [9 3] (row 1, col 3; and row 0, col 2)
Boolean indexing
You can also access only elements in an array with a boolean np.ndarray
as its indices.
x = np.array([1, 2, 3, 4, 5])
condition = np.array([True, False, False, True, True])
print(x[condition]) # [1 4 5] (only keep elements that are True)
This is mainly useful for filtering your arrays. Possibly one of the most useful features that you may end up using a lot!
y = np.array([[1, 2, 3, 5], [-1, 4, 7, 9]])
print(y[y < 4])
## [1 2 3 -1] (Keep only elements that are <4)
print(y[(y < 4) & (y > 1)])
## [2 3] (Keep elements that are <4 and >1).
## (Note the paranthesis - you will get errors otherwise because of operator precedence)
print(y[np.logical_and(y < 4, y > 1)])
## Same as above
More advanced indexing techniques are covered in the official documentation.