Python Numpy; difference between colon and ellipsis indexing

Question:

I have been experimenting with Numpy array indexing using both colon and ellipsis. However, I cannot understand the results that I am getting.

Below is the example code:

>>> a = np.array([[1,2],[3,4]])
>>> a
array([[1, 2],
       [3, 4]])

>>> a[:,np.newaxis]     #  <-- the shape of the rows are unchanged
array([[[1, 2]],

       [[3, 4]]])
>>> a[...,np.newaxis]   #  <-- the shape of the rows changed from horizontal to vertical
array([[[1],
        [2]],

       [[3],
        [4]]])
Asked By: ckong80

||

Answers:

The original is (2,2)

With :, it becomes (2,1,2). The new axis added after the first dimension.

With … the shape is (2,2,1), the new shape is added last.

Answered By: hpaulj
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.