user9007131
user9007131

Reputation: 29

Different shapes for the 'same' parts of ndarray

I'm considering a numpy array:

import numpy as np
b = np.empty((10,11,12))

Now I would expect the following shapes to be the same, but they apparently are not:

>>> b[0,:,1].shape
>>> (11,)

and

>>> b[0][:][1].shape
>>> (12,)

Can somebody explain to me why the shapes are different? I read the Numpy documentation on indexing but there it says that writing a[k][l] is the same as a[k,l].

Upvotes: 2

Views: 42

Answers (1)

fuglede
fuglede

Reputation: 18211

This happens because b[0][:] is a view of b[0], so that b[0][:][1] is really b[0, 1, :]. A numeric example may help to highlight what is going on:

In [5]: b = np.arange(3*4*5).reshape((3, 4, 5))

In [6]: b[0]
Out[6]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [7]: b[0, :]
Out[7]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [8]: b[0, :, 1]
Out[8]: array([ 1,  6, 11, 16])

In [10]: b[0][:]
Out[10]:
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

In [11]: b[0][:][1]
Out[11]: array([5, 6, 7, 8, 9])

In [13]: b[0, 1, :]
Out[13]: array([5, 6, 7, 8, 9])

In [32]: b[0][:, 1]
Out[32]: array([ 1,  6, 11, 16])

Upvotes: 4

Related Questions