t1e2a2p6
t1e2a2p6

Reputation: 1

Can someone explain this numpy slicing behaviour?

Could someone explain me why the second assertion below fails? I do not understand why using a slice or a range for indexing would make a difference in this case.

import numpy as np

d = np.zeros(shape = (1,2,3))
assert d[:, 0, slice(0,2)].shape == d[:, 0, range(0,2)].shape #This doesn't trigger an exception as both operands return (1,2)
assert d[0, :, slice(0,2)].shape == d[0, :, range(0,2)].shape #This does because (1,2) != (2,1)...

Upvotes: 0

Views: 29

Answers (1)

hpaulj
hpaulj

Reputation: 231355

Make the array more diagnostic:

In [66]: d = np.arange(6).reshape(1,2,3)
In [67]: d
Out[67]: 
array([[[0, 1, 2],
        [3, 4, 5]]])

scalar index in the middle:

In [68]: d[:,0,:2]
Out[68]: array([[0, 1]])
In [69]: d[:,0,range(2)]
Out[69]: array([[0, 1]])

Shape is (1,2) for both, though the 2nd is a copy because of the advanced indexing of the last dimension.

Shape is the same in the 2nd set, but the order actually differs:

In [70]: d[0,:,:2]
Out[70]: 
array([[0, 1],
       [3, 4]])
In [71]: d[0,:,range(2)]
Out[71]: 
array([[0, 3],
       [1, 4]])

[71] is a case of mixed basic and advanced indexing, which is documented as doing the unexpected. The middle sliced dimension is put last.

https://numpy.org/doc/stable/reference/arrays.indexing.html#combining-advanced-and-basic-indexing

Upvotes: 1

Related Questions