Imperator123
Imperator123

Reputation: 609

How does numpy three dimensiona slicing and indexing and ellipsis work?

I'm having a hard time understanding how some of numpy's slicing and indexing works

First one is the following:

>>> x = np.array([[[1],[2],[3]], [[4],[5],[6]]])
>>> x.shape
(2, 3, 1)
>>> x[1:2]
array([[[4],
        [5],
        [6]]])

According to the documentation,

If the number of objects in the selection tuple is less than N , then : is assumed for any subsequent dimensions.

So does that means [[1], [2], [3]] , [[4], [5], [6]] is a 2x3 array itself?

And how does

x[1:2]

return

array([[[4],
        [5],
        [6]]])

?

The second is ellipsis,

>>> x[...,0]
array([[1, 2, 3],
       [4, 5, 6]])

Ellipsis expand to the number of : objects needed to make a selection tuple of the same length as x.ndim. There may only be a single ellipsis present.

Why does [...,0] means?

Upvotes: 0

Views: 198

Answers (2)

Jhon Doe
Jhon Doe

Reputation: 113

Now, when you execute x[1:2], it just hands you over the first slice.

My question is shouldn't it be second slice. As the output is slice 2

In [42]: x[1:2]
Out[42]: 
array([[[4],
        [5],
        [6]]])

Upvotes: 0

kmario23
kmario23

Reputation: 61325

For your first question, it means that x of shape (2, 3, 1) has 2 slices of 3x1 arrays.

In [40]: x
Out[40]: 
array([[[1],
        [2],          # <= slice 1 of shape 3x1
        [3]],

       [[4],
        [5],          # <= slice 2 of shape 3x1
        [6]]])

Now, when you execute x[1:2], it just hands you over the first slice but not including the second slice since in Python & NumPy it's always left inclusive and right exclusive (something like half-open interval, i.e. [1,2) )

In [42]: x[1:2]
Out[42]: 
array([[[4],
        [5],
        [6]]])

This is why you just get the first slice.

For your second question,

In [45]: x.ndim
Out[45]: 3

So, when you use ellipsis, it just stretches out your array to size 3.

In [47]: x[...,0]
Out[47]: 
array([[1, 2, 3],
       [4, 5, 6]])

The above code means, you take both slices from the array x, and stretch it row-wise.

But instead, if you do

In [49]: x[0, ..., 0]
Out[49]: array([1, 2, 3])

Here, you just take the first slice from x and stretch it row-wise.

Upvotes: 1

Related Questions