# numpy: Indexing¶

In :
import numpy as np

In :
a = np.random.rand(3,4,5)
a.shape

Out:
(3, 4, 5)

What's the result of this?

In :
a.shape

Out:
(4, 5)

And this?

In :
a[...,2].shape

Out:
(3, 4)
In :
a[1,0,3]

Out:
0.025588609438720655

Like all other things in Python, numpy indexes from 0.

In :
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
In :
a[:,2].shape

Out:
(3, 5)

Indexing into numpy arrays usually results in a so-called view.

In :
a = np.zeros((4,4))
a

Out:
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.

In :
b = a[:2,:2]

b

Out:
array([[ 0.,  0.],
[ 0.,  0.]])

What happens if we change b?

In :
b[1,0] = 5

b

Out:
array([[ 0.,  0.],
[ 5.,  0.]])
In :
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().

In :
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:

In :
a = np.random.rand(4,4)
a

Out:
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]])
In :
i = np.array([0,2])

a[i]

Out:
array([[ 0.94747406,  0.89080192,  0.46799144,  0.54340544],
[ 0.06203009,  0.7958913 ,  0.93468584,  0.88864481]])

And with conditionals:

In :
a>0.5

Out:
array([[ True,  True, False,  True],
[ True, False,  True,  True],
[False,  True,  True,  True],
[ True,  True,  True, False]], dtype=bool)
In :
a[a>0.5]

Out:
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])