Create a row vector
Convert a flat vector into a row-shaped array for operations that expect a leading batch or row dimension.
NumPy · Function
Adds one or more singleton dimensions to an array at specified axis positions. The result is an ndarray view, and a tuple of axes can insert multiple dimensions.
np.expand_dims returns a view of the input with one additional dimension when axis is an integer, or additional dimensions when axis is a tuple. The inserted dimensions have length one, and axis positions determine where they appear in the resulting shape.
numpy.expand_dims(a, axis)| Name | Type | Description |
|---|---|---|
a | array_like | Input array. |
axis | int or tuple of ints | Position in the expanded axes where the new axis or axes is placed. |
res — ndarray: A view of a with the number of dimensions increased by one for a single axis; tuple axes add one dimension per axis.
import numpy as np
x = np.array([1, 2])
rows = np.expand_dims(x, axis=0)
columns = np.expand_dims(x, axis=1)
print(rows.shape) # (1, 2)
print(columns.shape) # (2, 1)Adds a leading or trailing singleton dimension to make a one-dimensional array row- or column-shaped.
Convert a flat vector into a row-shaped array for operations that expect a leading batch or row dimension.
Convert a flat vector into a column-shaped array for matrix multiplication or broadcasting.
Insert several singleton dimensions at once when aligning shapes for broadcasting.
It inserts singleton dimensions at the requested axis positions and returns a view of the input. With an integer axis, the rank increases by one; a tuple can insert several dimensions.
Follow-up: How would you create a column vector from a one-dimensional array? Use np.expand_dims(x, axis=1), which is equivalent to x[:, np.newaxis].
axis specifies where the new dimension is placed in the expanded shape. For a one-dimensional array, axis=0 produces shape (1, n), while axis=1 produces (n, 1).
Follow-up: Can axis be repeated in a tuple? No; each axis must be unique, otherwise NumPy raises a ValueError.
The function accepts an array-like input and an integer or tuple of integers for axis. A tuple inserts one new dimension for each supplied axis, allowing multiple dimensions to be added in one call.
Follow-up: What alternatives express a single-axis expansion? Indexing with np.newaxis or None can express equivalent reshaping operations.
numpy.newaxisnumpy.squeezenumpy.reshapenumpy.atleast_1dnumpy.atleast_2dnumpy.atleast_3d