1

I came across a code where the author have used the ellipsis operator (e.g., [..., 1]) with numpy array instead of a slice operator (e.g., [:, 1]) to get arrays part.

My research on the subject:

  1. From scipy github wiki page I've learned that both operators perform somewhat similar operations, i.e. return a slice of a multidimensional array.

  2. I've went over this question, which have dealt with several slicing techniques of numpy arrays, but did not find the elaboration regarding the situation when should you use slice operator and when it is necessary to use the ellipsis, or if their functionality is identical.

  3. From Example 1 I can't spot any difference between the two operators:

Example 1:

    import numpy as np

    A = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    A[..., 0], A[:, 0]    # Out: (array([1, 4, 7]), array([1, 4, 7]))
    A[..., 0] == A[:, 0]  # Out: array([ True,  True,  True])

So my question is:

  • What is the difference in using the slice vs ellipsis operator with the numpy.ndarrays?
  • Can they be used interchangeably?
  • Is there any advantages in using one or the other?

I'd really appreciate an elaboration regarding my question, and thanks in advance for your time.

Michael
  • 2,167
  • 5
  • 23
  • 38

1 Answers1

4

The motivations behind the two are completely different.

  • The ellipsis means "all the other dimensions (which I can't be bothered to enumerate or am unsure or don't care how many there are) in their entirety"

  • the slice means "the subset of the current dimension as specified by the starting and ending indices (and stride)".

Mark Setchell
  • 191,897
  • 31
  • 273
  • 432
  • 1
    I see, but can they be used interchangeably in the case of the `Example 1`? – Michael Aug 08 '20 at 17:19
  • 2
    Not really. `[..., 1]` could mean `[:,1]` or `[:,:,:,:,1]` – Mark Setchell Aug 08 '20 at 17:24
  • 1
    So why then the outputs are identical? I mean - is there a situation where the outputs would be different? – Michael Aug 10 '20 at 14:22
  • 1
    That's rather like saying `2+2` gives the same result as `2x2` therefore the plus and the times operator must be the same. On occasion they can give the same result, but in general they won't. If you do `A = np.zeros((8,6,4))` then print `A[:,1].shape` you'll see it is `(8, 4)` but if you print `A[...,1].shape` you'll see it is `(8,6)`. – Mark Setchell Aug 10 '20 at 17:19