Create batches
Representing multiple same-shaped observations as one batch dimension.
NumPy · Function
Stacks a sequence of equally shaped arrays along a new axis. Use axis to choose where that dimension appears, and optionally provide an output buffer, dtype, and casting policy.
np.stack converts a sequence of equally shaped arrays into one array by inserting a new dimension at the position selected by axis. With axis=0 the new dimension leads the result; with axis=-1 it trails it. The optional out buffer receives the result, while dtype and casting control conversion.
numpy.stack(arrays, axis=0, out=None, *, dtype=None, casting='same_kind')| Name | Type | Description |
|---|---|---|
arrays | sequence of array_like | Sequence of array-like inputs to stack; each input must have the same shape. |
axis | int, optional | Position of the new axis in the result. The default is 0. |
out | ndarray, optional | Optional destination array for the result. |
dtype | dtype, optional | Optional data type for the result. |
casting | {‘no’, ‘equiv’, ‘safe’, ‘same_kind’, ‘unsafe’}, optional | Controls permitted data casting. |
An ndarray containing the input arrays stacked along the newly inserted axis.
import numpy as np
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
rows = np.stack((a, b))
columns = np.stack((a, b), axis=-1)
print(rows)
print(columns)Creates one two-dimensional array by inserting a leading axis, then another by inserting the new axis at the end.
Representing multiple same-shaped observations as one batch dimension.
Choosing whether the sample dimension leads or trails existing dimensions.
Writing results into caller-managed storage.
np.stack joins a sequence of arrays along a newly created axis. If the inputs have shape (M, N), stacking K of them produces a result with K elements in the inserted dimension.
Follow-up: How does axis=-1 differ from the default? It places the new dimension at the end rather than at the beginning.
The default axis is 0, so the new dimension becomes the first dimension of the result. For ten inputs of shape (3, 4), the result therefore has shape (10, 3, 4).
Follow-up: What shape results from axis=1 for those inputs? The shape is (3, 10, 4).
arrays is a sequence of array-like values, and every member must have the same shape. out may provide the destination array; dtype selects the result type and casting controls permitted conversions.
Follow-up: When would out be useful? It lets callers place the computed result into a preallocated destination instead of relying only on a newly returned allocation.
numpy.concatenatenumpy.stacknumpy.blocknumpy.vstacknumpy.hstacknumpy.dstack