Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Numpy; difference between colon and ellipsis indexing

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]]])
like image 314
ckong80 Avatar asked Aug 01 '26 05:08

ckong80


1 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.

like image 59
hpaulj Avatar answered Aug 02 '26 18:08

hpaulj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!