Understand NumPy Array Three Dots(…) or Ellipsis with Examples – NumPy Tutorial

By | January 11, 2024

We may find three dots (…) or ellipsis when get numpy ndarray elements. For example:

  1. shift_logits = logits[..., :-1, :]
  2. shift_labels = labels[..., 1:]
shift_logits = logits[..., :-1, :]
shift_labels = labels[..., 1:]

What this ellipsis means? In this tutorial, we will use an example to show you.

For example:

  1. import numpy as np
  2. x = np.arange(0,32).reshape(2, 4, 4)
  3. print("x =")
  4. print(x)
  5. print("x[:,:, 1] = ")
  6. print(x[:,:, 1])
  7. print("x[..., 1] = ")
  8. print(x[..., 1])
import numpy as np

x = np.arange(0,32).reshape(2, 4, 4)
print("x =")
print(x)

print("x[:,:, 1] = ")
print(x[:,:, 1])

print("x[..., 1] = ")
print(x[..., 1])

Run this code, we will see this result.

  1. x =
  2. [[[ 0 1 2 3]
  3. [ 4 5 6 7]
  4. [ 8 9 10 11]
  5. [12 13 14 15]]
  6. [[16 17 18 19]
  7. [20 21 22 23]
  8. [24 25 26 27]
  9. [28 29 30 31]]]
  10. x[:,:, 1] =
  11. [[ 1 5 9 13]
  12. [17 21 25 29]]
  13. x[..., 1] =
  14. [[ 1 5 9 13]
  15. [17 21 25 29]]
x =
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]
  [12 13 14 15]]

 [[16 17 18 19]
  [20 21 22 23]
  [24 25 26 27]
  [28 29 30 31]]]
x[:,:, 1] = 
[[ 1  5  9 13]
 [17 21 25 29]]
x[..., 1] = 
[[ 1  5  9 13]
 [17 21 25 29]]

From the result above, we can find:

x[:,:, 1] == x[…, 1]

Actually, ellipsis mean :,:,…,: from the beginning and :,:,…,: from the ending.

For example:

if the shape of x is [3,4,5,6,]

x[:,:,2:3,:] = […,2:3,…]