note.nkmk.me

NumPy: Ellipsis (...) for ndarray

Posted: 2020-09-25 / Tags: Python, NumPy

When specifying an element or range with [] of the NumPy array numpy.ndarray, you can use the Python built-in constant Ellipsis (...).

This post describes the following:

  • Python built-in constant Ellipsis (...)
  • Using Ellipsis (...) in NumPy

The sample code below is for Python3 (3.7.2). Note that the behavior may be different in Python2.

Sponsored Link

Python built-in constant Ellipsis (...)

In Python3, Ellipsis is defined as a built-in constant.

print(Ellipsis)
# Ellipsis

Ellipsis can also be described as ... (3 dots).

print(...)
# Ellipsis

Ellipsis and ... are the same ellipsis object.

print(type(Ellipsis))
# <class 'ellipsis'>

print(type(...))
# <class 'ellipsis'>

print(Ellipsis is ...)
# True

As of Python 3.7.2, there is no particular use for Ellipsis (...) as the basic grammar of Python, but as shown below, NumPy has a convenient way to use Ellipsis (...).

Using Ellipsis (...) in NumPy

In NumPy, you can use Ellipsis (...) to omit intermediate dimensions when specifying elements or ranges with [].

Take the following four-dimensional array as an example.

import numpy as np

a = np.arange(120).reshape(2, 3, 4, 5)

print(a.shape)
# (2, 3, 4, 5)

For example, if you want to specify only the last dimension, you can use :.

print(a[:, :, :, 0])
# [[[  0   5  10  15]
#   [ 20  25  30  35]
#   [ 40  45  50  55]]
# 
#  [[ 60  65  70  75]
#   [ 80  85  90  95]
#   [100 105 110 115]]]

With ..., you can write:

print(a[..., 0])
# [[[  0   5  10  15]
#   [ 20  25  30  35]
#   [ 40  45  50  55]]
# 
#  [[ 60  65  70  75]
#   [ 80  85  90  95]
#   [100 105 110 115]]]

The same applies when you want to specify only the first and last dimensions. You can omit the dimension in the middle with ....

print(a[0, :, :, 0])
# [[ 0  5 10 15]
#  [20 25 30 35]
#  [40 45 50 55]]

print(a[0, ..., 0])
# [[ 0  5 10 15]
#  [20 25 30 35]
#  [40 45 50 55]]

You may use Ellipsis instead of ....

print(a[Ellipsis, 0])
# [[[  0   5  10  15]
#   [ 20  25  30  35]
#   [ 40  45  50  55]]
# 
#  [[ 60  65  70  75]
#   [ 80  85  90  95]
#   [100 105 110 115]]]

print(a[0, Ellipsis, 0])
# [[ 0  5 10 15]
#  [20 25 30 35]
#  [40 45 50 55]]

With :, the number of : must be matched to the number of dimensions, but you do not have to worry about it as ....

If there are two or more ..., it is not clear where to omit, so an error will occur.

# print(a[..., 0, ...])
# IndexError: an index can only have a single ellipsis ('...')

If : is repeated up to the last dimension, : can be omitted. There is no need to write ....

print(a[0, 0, :, :])
# [[ 0  1  2  3  4]
#  [ 5  6  7  8  9]
#  [10 11 12 13 14]
#  [15 16 17 18 19]]

print(a[0, 0])
# [[ 0  1  2  3  4]
#  [ 5  6  7  8  9]
#  [10 11 12 13 14]
#  [15 16 17 18 19]]

print(a[0, 0, ...])
# [[ 0  1  2  3  4]
#  [ 5  6  7  8  9]
#  [10 11 12 13 14]
#  [15 16 17 18 19]]
Sponsored Link
Share

Related Categories

Related Posts