Append along a selected axis
Add records to a two-dimensional dataset while preserving rows.
NumPy · Function
Appends values to an array and returns a new ndarray. Without axis, both inputs are flattened; with axis, values must have compatible dimensions.
numpy.append creates and returns a new array containing values after arr. With axis omitted or set to None, both inputs are flattened first; with an axis supplied, values must match arr in every other dimension.
numpy.append(arr, values, axis=None)| Name | Type | Description |
|---|---|---|
arr | array_like | Array-like object whose contents receive the appended values. |
values | array_like | Array-like data to append; its shape must be compatible when axis is specified. |
axis | int, optional | Optional dimension along which to append. If omitted, both inputs are flattened. |
ndarray: a copy of arr with values appended along axis; when axis is None, the result is flattened.
import numpy as np
rows = np.array([[1, 2], [3, 4]])
result = np.append(rows, [[5, 6]], axis=0)
print(result)
Adds one row along axis 0 and leaves the input array unchanged.
Add records to a two-dimensional dataset while preserving rows.
Combine one-dimensional data with additional elements.
Produce a flat sequence from inputs with differing shapes.
It returns a new ndarray with values placed after arr. The original array is not changed because a new array is allocated.
Follow-up: What happens when axis is None? Both arr and values are flattened, and the result is one-dimensional.
With axis omitted, both inputs are flattened before appending. The result is therefore a flattened array.
Follow-up: How do you preserve rows in a two-dimensional array? Supply the axis, such as axis=0, and provide values with a compatible shape.
axis selects the dimension along which values are appended. Values must match arr in shape for all dimensions other than that axis.
Follow-up: Why might an append fail with axis=0? A non-axis dimension differs, so the values do not have the required compatible shape.
numpy.concatenatenumpy.stacknumpy.ma.append