import numpy as np
A = np.array([[1, 4, 9], [2, 8, 18]])
print(A)
A[1,2]
What's the result of this?
A[:,1]
And this?
A[1:,:1]
One more:
A[:,[0,2]]
For higher-dimensional arrays we can use ...
like:
a = np.random.rand(3,4,2)
a.shape
a[...,1].shape
Indexing into numpy arrays usually results in a so-called view.
a = np.zeros((4,4))
Let's call b
the top-left $2\times 2$ submatrix.
b = a[:2,:2]
What happens if we change b
?
b[1,0] = 5
a
To decouple b
from a
, use .copy()
.
b = b.copy()
b[1,1] = 7
print(b)
print(a)
You can also index with boolean arrays:
a = np.random.rand(4,4)
a
a_big = a>0.5
a_big
a[a_big]
Also each index individually:
a_row_sel = [True, True, False, True]
a[a_row_sel,:]
And with index arrays:
a
x,y = np.nonzero(a > 0.5)
x
y
a[(x,y)]