Positional sequence insertion
Add one or more records at a known position in a one-dimensional array.
NumPy · Function
Inserts values before selected indices in an array, optionally along a specified axis. It returns a new array rather than modifying the input.
np.insert creates a new array by placing values before the positions described by obj along the selected axis. With axis=None, it flattens arr first; values are converted to arr's dtype when necessary, and the input is not modified.
numpy.insert(arr, obj, values, axis=None)| Name | Type | Description |
|---|---|---|
arr | array_like | Input array. |
obj | slice, int, array-like of ints or bools | Object defining the index or indices before which values is inserted. |
values | array_like | Values to insert into arr; differing types are converted to arr's type. |
axis | int, optional | Axis along which to insert values. If None, arr is flattened first. |
out ndarray — A copy of arr with values inserted. If axis is None, out is a flattened array.
import numpy as np
arr = np.array([[1, 2], [3, 4]])
result = np.insert(arr, 1, [9, 8], axis=0)
print(result)
# [[1 2]
# [9 8]
# [3 4]]Inserts one row before row index 1 and leaves the original array unchanged.
Add one or more records at a known position in a one-dimensional array.
Add a row or column to a matrix while preserving the original matrix.
Create a flattened sequence with additional values before chosen positions.
np.insert(arr, obj, values, axis=None) returns a copy with values inserted before the indices specified by obj. The insertion occurs along axis when one is supplied; otherwise arr is flattened.
Follow-up: What happens to the source array? It is not modified, because np.insert returns a new array.
arr is the input array, obj specifies an index, slice, or integer indices before which insertion occurs, and values supplies the inserted data. axis selects the dimension, while None requests flattening.
Follow-up: How should values be prepared for multidimensional insertion? Its shape must make the corresponding indexed assignment valid.
The result is an ndarray containing the inserted values, and it is a copy rather than an in-place modification. When axis is None, the returned array is flattened.
Follow-up: What dtype will inserted values have if it differs from arr? They are converted to arr's dtype.
numpy.appendnumpy.concatenatenumpy.deletenumpy.pad