Sub topic 4
Ellipsis and np.newaxis
This chapter assumes you can already index and slice NumPy arrays with start:stop:step, and that you know what shape means. Two small tools extend slicing. ... (Ellipsis) stands in for "all the remaining axes". np.newaxis inserts a new axis of length 1.
Ellipsis: skipping axes you don't care about
In a 3-D array, selecting the last axis with plain slices needs a[:, :, 0]. In a 5-D array you would need four colons. The Ellipsis ... expands to as many : slices as it takes to cover every axis you did not index explicitly.
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, ..., 1]) # [1 5 9], same as a[0, :, 1]
print(np.array_equal(a[..., 0], a[:, :, 0])) # TrueThe Ellipsis can sit at the start, middle, or end of the index. It is most useful when code must work for arrays with different numbers of dimensions. For example, x[..., -1] takes the last element along the last axis whether x is 2-D or 5-D.
Like any basic slice, an Ellipsis index returns a view, so writes show through to the original array.
np.newaxis: adding an axis of length 1
np.newaxis is another name for None. Put it in an index where you want a new axis of length 1. It does not consume any existing axis.
import numpy as np
x = np.array([1, 2, 3])
print(x.shape) # (3,)
col = x[:, np.newaxis]
row = x[np.newaxis, :]
print(col.shape) # (3, 1)
print(row.shape) # (1, 3)
print(col * row)
# [[1 2 3]
# [2 4 6]
# [3 6 9]]
print(x[:, None].shape) # (3, 1), None means the same thing
print(np.shares_memory(x, col)) # True, still a viewThe product works through broadcasting, which is NumPy's rule for combining arrays of different shapes. A (3, 1) array and a (1, 3) array both stretch to (3, 3). A plain 1-D array has no way to say "this is a column", so np.newaxis is the usual way to make that choice explicit.
Where you write np.newaxis decides which position the new axis takes:
| Expression (x has shape `(3,)`) | Result shape |
|---|---|
| `x[np.newaxis, :]` | `(1, 3)` |
| `x[:, np.newaxis]` | `(3, 1)` |
| `x[np.newaxis]` | `(1, 3)` |
| `x[np.newaxis, :, np.newaxis]` | `(1, 3, 1)` |
Using both together
The two tools combine well. a[..., np.newaxis] appends a length-1 axis to an array of any dimensionality. This is a common way to prepare an array for broadcasting against another array that has one more dimension.
import numpy as np
a = np.arange(24).reshape(2, 3, 4)
print(a[..., np.newaxis].shape) # (2, 3, 4, 1)
print(a[np.newaxis, ...].shape) # (1, 2, 3, 4)
print(a[:, np.newaxis, ..., 0].shape) # (2, 1, 3)The last line is worth reading slowly. The explicit indices are : and 0, which cover two axes. The Ellipsis therefore expands to one :. The np.newaxis does not count toward the axes covered. The result has axis 0 kept (2), a new axis (1), axis 1 kept (3), and axis 2 removed by the integer 0.
Common errors
- Counting
np.newaxisas a real axis. It adds a dimension and never uses one up. If you add one to an index, the Ellipsis still expands to the same number of colons. - Two Ellipses in one index. This raises an IndexError. Use one
...and write explicit colons for the rest. - Expecting a copy. Both tools return views. Use
.copy()if you will modify the result and want the original left alone. - Forgetting the shape after the new axis. Print
.shapewhen a broadcast gives an unexpected result. A(3,)plus(3, 1)gives(3, 3), not(3,).
Exercise
An array a has shape (2, 3, 4). What is the shape of a[..., np.newaxis, 1], and why?
Show answer
The shape is (2, 3, 1). The integer 1 uses up the last axis (length 4) and removes it. The Ellipsis expands to :, : for the first two axes, which keeps shapes 2 and 3. The np.newaxis then adds a length-1 axis after them.
Exercise
Given x = np.array([10, 20, 30]), write one expression using np.newaxis that gives the 3x3 table of differences x[i] - x[j], with row i and column j.
Show answer
x[:, np.newaxis] - x[np.newaxis, :]. The (3, 1) column broadcasts against the (1, 3) row to give a (3, 3) result.