Home > other >  What does a [..., 0] mean in python array?
What does a [..., 0] mean in python array?

Time:12-27

What is the meaning of ... in a python array? The code below is what it was written like.

 obj = target[..., 0 ]

Please help me!

CodePudding user response:

Ellipsis expands to all other dimensions.

From numpy's documentation:

Ellipsis expands to the number of : objects needed for the selection tuple to index all dimensions.

Example for a 3 dimensional shape:

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

You can see that the first item of the third dimension was picked across all others. Since it contains only 1 item and is not a slice, it was expanded.

CodePudding user response:

In numpy arrays, an ellipsis (...) is the equivalent of a column (:) in that they allow array slicing like in the example below where I create a 2D numpy array and print its columns as 1D array:

import numpy as np

x = np.array(range(12)).reshape(3,4)
print(f'x = {x}')
print(f'\nSlicing with ellipsis \t Slicing with column')
for i in range(x.shape[1]):
    print(f'{x[...,i]} \t\t {x[:,i]}')

The output of this code is:

[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]]

Slicing with ellipsis    Slicing with column
[0 4 8]                  [0 4 8]
[1 5 9]                  [1 5 9]
[ 2  6 10]               [ 2  6 10]
[ 3  7 11]               [ 3  7 11]

The same could be done on rows using x[i,:] or its equivalent x[i,...].

  • Related