import numpy as np
a = np.random.rand(3,4,5)
a.shape
(3, 4, 5)
What's the result of this?
a[0].shape
(4, 5)
And this?
a[...,2].shape
(3, 4)
a[1,0,3]
0.025588609438720655
Like all other things in Python, numpy indexes from 0.
a[3,2,2].shape
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-6-4c22dfd164ed> in <module>() 1 #keep ----> 2 a[3,2,2].shape IndexError: index 3 is out of bounds for axis 0 with size 3
a[:,2].shape
(3, 5)
Indexing into numpy arrays usually results in a so-called view.
a = np.zeros((4,4))
a
array([[ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.], [ 0., 0., 0., 0.]])
Let's call b
the top-left $2\times 2$ submatrix.
b = a[:2,:2]
b
array([[ 0., 0.], [ 0., 0.]])
What happens if we change b
?
b[1,0] = 5
b
array([[ 0., 0.], [ 5., 0.]])
print(a)
[[ 0. 0. 0. 0.] [ 5. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]]
To decouple b
from a
, use .copy()
.
b = b.copy()
b[1,1] = 7
print(a)
[[ 0. 0. 0. 0.] [ 5. 0. 0. 0.] [ 0. 0. 0. 0.] [ 0. 0. 0. 0.]]
You can also index with other arrays:
a = np.random.rand(4,4)
a
array([[ 0.94747406, 0.89080192, 0.46799144, 0.54340544], [ 0.54409333, 0.27586608, 0.60682897, 0.61962813], [ 0.06203009, 0.7958913 , 0.93468584, 0.88864481], [ 0.98627827, 0.73442815, 0.90304704, 0.18186312]])
i = np.array([0,2])
a[i]
array([[ 0.94747406, 0.89080192, 0.46799144, 0.54340544], [ 0.06203009, 0.7958913 , 0.93468584, 0.88864481]])
And with conditionals:
a>0.5
array([[ True, True, False, True], [ True, False, True, True], [False, True, True, True], [ True, True, True, False]], dtype=bool)
a[a>0.5]
array([ 0.94747406, 0.89080192, 0.54340544, 0.54409333, 0.60682897, 0.61962813, 0.7958913 , 0.93468584, 0.88864481, 0.98627827, 0.73442815, 0.90304704])