Ryan
Ryan

Reputation: 8241

Array indexing in NumPy not making sense

I have a numpy array of size 28x28x60000. Observe the following:

>>> X.shape
(28, 28, 60000)
>>> X[:][:][0].shape
(28, 60000)

Shouldn't X[:][:][0] be an array of size 28x28? We are including every component from the first two dimensions (28 each), but only the 0th entry from the third.

What is going on here?

Upvotes: 2

Views: 470

Answers (2)

Anton Protopopov
Anton Protopopov

Reputation: 31692

You slicing wrong. Slice X[:] return the copy of the original array. So your slicing could be interpreted as 1st copy of the X, then another copy of the X and then get first element which has 28x60000 shape. So you need to call X[:,:,0]. Example:

import numpy as np
X = np.random.randn(28,28,60000)

In [257]: X[:,:,0].shape
Out[257]: (28, 28)

You could compare your X[:] and X[:][:] statements with all

In [261]: (X[:] == X[:][:]).all()
Out[261]: True

Upvotes: 6

grg rsr
grg rsr

Reputation: 568

X[:] indexes into all values from all dimensions, not just the first. So X[:][:] is identical to X

To get your result, you simply write X[:,:,0]

Upvotes: 3

Related Questions