Sub topic 4
Ellipsis and np.newaxis
Two small index tokens complete the basic indexing toolkit. ... (the Ellipsis) stands in for "all the axes I don't want to spell out". np.newaxis inserts a new axis of length 1. The first makes code independent of how many dimensions an array has. The second is how you line up arrays of different shapes for broadcasting.
This chapter assumes you can create arrays with np.arange and reshape, read an array's shape, and use integer indices and start:stop:step slices on multi-dimensional arrays. It also assumes you know the basic broadcasting rule: shapes are compared from the right, and a length-1 axis stretches to match.
Ellipsis: filling in the axes you skip
In Python, ... is a built-in singleton called Ellipsis. Python itself gives it no meaning. NumPy interprets it inside an index as "as many full slices (:) as are needed to make the index cover every axis".
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[..., 0].shape) # (2, 3) same as a[:, :, 0]
print(a[0, ...].shape) # (3, 4) same as a[0, :, :]
print(a[0, ..., 0].shape) # (3,) same as a[0, :, 0]
print(a[...].shape) # (2, 3, 4) same as a[:, :, :]The Ellipsis expands to fill the gap between the indices written before it and the ones written after it. In a[0, ..., 0], the first 0 addresses axis 0 and the last 0 addresses the final axis. The Ellipsis takes everything in between. For a 3-D array that is one axis. For a 5-D array it would be three.
Why use it
Writing a[:, :, 0] hard-codes the number of dimensions. It breaks when the same function receives a 2-D or 4-D array. a[..., 0] always means "the last axis, index 0", whatever the dimensionality.
import numpy as np
def flip_last(x):
"""Reverse the order along the final axis, for any number of dimensions."""
return x[..., ::-1]
print(flip_last(np.array([1, 2, 3]))) # [3 2 1]
print(flip_last(np.arange(6).reshape(2, 3))) # [[2 1 0]
# [5 4 3]]
print(flip_last(np.arange(24).reshape(2, 3, 4))[0, 0]) # [3 2 1 0]This pattern is common in code that processes the "last axis" of data. Examples are the channel axis of images, the feature axis of a batch, and the time axis of signals.
Rules and edge cases
- An index may contain at most one Ellipsis. With two, NumPy cannot decide how many axes each one covers and raises
IndexError: an index can only have a single ellipsis ('...'). - The Ellipsis can match zero axes. If the other indices already address every axis,
...expands to nothing. - Indexing every axis with integers normally returns a scalar. Adding an Ellipsis changes that to a 0-dimensional array.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(type(a[1, 2, 3]).__name__) # int64
print(type(a[1, 2, 3, ...]).__name__) # ndarray
print(a[1, 2, 3, ...].shape) # ()The 0-d array result is a view into a, not a copy. Because of this, a[1, 2, 3, ...] = 0 is a way to write through an index that would otherwise return a plain scalar. In fact a[1, 2, 3] = 0 already works as assignment, so this matters mainly when you need a live reference to a single cell.
A basic index containing an Ellipsis is still basic indexing. It returns a view that shares memory with the original array, as described in the chapter on views and copies.
np.newaxis: inserting an axis of length 1
np.newaxis is an alias for None. Placing it in an index inserts a new axis of length 1 at that position. It does not consume any existing axis and does not change the data.
import numpy as np
v = np.array([1, 2, 3])
print(v.shape) # (3,)
col = v[:, np.newaxis]
row = v[np.newaxis, :]
print(col.shape, row.shape) # (3, 1) (1, 3)
print(col * row) # [[1 2 3]
# [2 4 6]
# [3 6 9]]
print(np.newaxis is None) # True
print(np.shares_memory(v, col)) # TrueRead v[:, np.newaxis] from left to right. The : keeps the existing axis, and np.newaxis adds a new trailing axis after it. The result is a column vector. v[np.newaxis, :] puts the new axis first, giving a row vector.
Multiplying a (3, 1) array by a (1, 3) array broadcasts both to (3, 3). This is an outer product, built without a loop.
The result is a view. No data is copied, so adding an axis costs almost nothing, even for a large array.
Pairwise differences
A second use is comparing every element of one array with every element of another. Here we compute all pairwise differences between the points of a single array.
import numpy as np
x = np.array([0.0, 1.0, 3.0])
diff = x[:, np.newaxis] - x[np.newaxis, :]
print(diff)
# [[ 0. -1. -3.]
# [ 1. 0. -2.]
# [ 3. 2. 0.]]Entry diff[i, j] equals x[i] - x[j]. The array with the new trailing axis supplies the row index i. The array with the new leading axis supplies the column index j.
Aligning axes for broadcasting
Broadcasting compares shapes from the right. A per-image statistic of shape (2,) cannot be subtracted from a stack of images of shape (2, 3, 4), because 2 is compared against 4. np.newaxis moves the statistic onto the correct axis.
import numpy as np
x = np.arange(24, dtype=float).reshape(2, 3, 4) # 2 "images", 3x4 each
means = x.mean(axis=(1, 2)) # shape (2,): [ 5.5 17.5]
# x - means would raise ValueError: operands could not be broadcast together
centered = x - means[:, np.newaxis, np.newaxis] # means now has shape (2, 1, 1)
print(np.allclose(centered.mean(axis=(1, 2)), 0.0)) # TrueThe reduction methods have a built-in alternative. x.mean(axis=(1, 2), keepdims=True) returns shape (2, 1, 1) directly. Use np.newaxis when the array did not come from a reduction, or when you need to build the shape yourself.
Combining Ellipsis and np.newaxis
np.newaxis and ... can appear in the same index. The Ellipsis counts only the axes of the original array that the other indices have not yet used. A np.newaxis does not use up an axis.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[np.newaxis].shape) # (1, 2, 3, 4)
print(a[..., np.newaxis].shape) # (2, 3, 4, 1)
print(a[:, np.newaxis].shape) # (2, 1, 3, 4)
print(a[np.newaxis, ..., 0].shape) # (1, 2, 3)Here is how the last one works. The 0 takes the final axis. The Ellipsis then covers the two remaining original axes, of lengths 2 and 3. The np.newaxis adds a leading axis, giving (1, 2, 3).
a[..., np.newaxis] is the standard idiom for "add a trailing axis to an array of any dimensionality". For example, x[..., np.newaxis] turns a (H, W) image into (H, W, 1) and a (N, H, W) batch into (N, H, W, 1) with the same code.
| Expression on `a` with shape `(2, 3, 4)` | Result shape | What it does |
|---|---|---|
| `a[0]` | `(3, 4)` | Integer removes axis 0 |
| `a[..., 0]` | `(2, 3)` | Integer removes the last axis |
| `a[0, ..., 0]` | `(3,)` | Integers remove the first and last axes |
| `a[np.newaxis]` | `(1, 2, 3, 4)` | New leading axis |
| `a[..., np.newaxis]` | `(2, 3, 4, 1)` | New trailing axis |
| `a[:, np.newaxis]` | `(2, 1, 3, 4)` | New axis after axis 0 |
| `a[np.newaxis, ..., 0]` | `(1, 2, 3)` | New leading axis, last axis removed |
newaxis versus reshape
v[:, np.newaxis] and v.reshape(-1, 1) give the same shape for a 1-D array. They differ in what they promise:
np.newaxisstates exactly where the new axis goes. It works on arrays of any dimensionality without recomputing sizes.reshape(-1, 1)flattens the meaning: it asserts the result is 2-D with one column. Applied to a 2-D array it silently re-lays-out all the elements instead of adding an axis.- Adding an axis with
np.newaxisalways returns a view.reshapereturns a view when it can and a copy when it must, which is harder to predict.
For "add a length-1 axis here", prefer np.newaxis.
Common mistakes
- Putting the new axis on the wrong side.
v[:, np.newaxis] - vandv - v[:, np.newaxis]give results that are transposes of each other, and flipping the sign convention by accident is easy. Check.shapeand a small example before trusting a larger one. - Forgetting that
np.newaxisis position-sensitive on N-D arrays. On a 2-D array of shape(3, 4),m[:, np.newaxis]has shape(3, 1, 4), not(3, 4, 1). To append, usem[..., np.newaxis]. - Using two Ellipses. An index such as
a[..., 0, ...]raisesIndexError. Replace one of them with explicit colons. - Expecting a scalar from
a[i, j, k, ...]. It returns a 0-d array. Convert with.item()if you need a Python number. - Writing
Nonewhen you meantnp.newaxis, or the reverse. They are the same object. Usenp.newaxisfor readability, since a bareNoneinside an index looks like a mistake to a reader.
Exercise
Given a = np.arange(24).reshape(2, 3, 4), what are the shapes of a[..., 1:3], a[1, ..., np.newaxis], and a[np.newaxis, :, 0, ...]?
Show answer
a[..., 1:3] has shape (2, 3, 2): the Ellipsis keeps axes 0 and 1 whole, and the slice 1:3 keeps two entries of the last axis. a[1, ..., np.newaxis] has shape (3, 4, 1): the integer removes axis 0, the Ellipsis keeps axes 1 and 2, and the new axis is appended. a[np.newaxis, :, 0, ...] has shape (1, 2, 4): the new leading axis has length 1, : keeps axis 0 (length 2), the 0 removes axis 1, and the Ellipsis keeps the last axis (length 4).
Exercise
You have heights = np.array([1.5, 1.7, 1.9]) and weights = np.array([50.0, 60.0, 70.0, 80.0]). Write one expression, without loops or reshape, that produces a (3, 4) array whose entry [i, j] is weights[j] / heights[i] ** 2. Which array needs the new axis, and where?
Show answer
weights[np.newaxis, :] / heights[:, np.newaxis] ** 2. The heights array needs a trailing axis to become shape (3, 1), so that index i runs down the rows. The weights array can stay as (4,) or become (1, 4), so that index j runs across the columns. Broadcasting stretches both to (3, 4). Note that ** binds tighter than /, so heights[:, np.newaxis] ** 2 is squared before the division.
Exercise
Why does a[..., 0, ...] fail, and how would you rewrite it for a 4-D array a if you wanted the second-to-last axis fixed at index 0?
Show answer
An index may contain only one Ellipsis, so NumPy raises IndexError because it cannot split the missing axes between two Ellipses. To fix the second-to-last axis, write a[..., 0, :]. The Ellipsis covers the leading axes, 0 addresses the second-to-last axis, and : keeps the final axis.