NumPy insert()
NumPy's insert()
function allows you to insert values into an array at specified indices, creating a new array with the inserted values. This operation is essential for dynamically modifying arrays when specific elements need to be added to certain positions.
Usage
The insert()
operation is used when you want to add elements into a NumPy array without modifying the original array. It returns a new array with the inserted values at the specified indices.
numpy.insert(arr, obj, values, axis=None)
arr
: The input array.obj
: The index or indices before whichvalues
are inserted. This can be an integer, a sequence of integers, or negative indices.values
: The values to insert intoarr
.axis
: Specifies the axis along which to insert. IfNone
, the array is flattened before insertion.
Examples
1. Basic Insert
import numpy as np
arr = np.array([1, 2, 3, 4])
# Insert 9 at index 2
new_arr = np.insert(arr, 2, 9)
# Resulting array: [1, 2, 9, 3, 4]
2. Insert with Axis
import numpy as np
arr = np.array([[1, 2], [3, 4]])
# Insert row [5, 6] before the second row
new_arr = np.insert(arr, 1, [5, 6], axis=0)
# Resulting array: [[1, 2], [5, 6], [3, 4]]
Note: If the shape of values
does not match the dimensions of the specified axis, an error will be raised.
3. Inserting Multiple Values
import numpy as np
arr = np.array([10, 20, 30])
# Insert 99 at index 1 and 88 at index 2
new_arr = np.insert(arr, [1, 2], [99, 88])
# Resulting array: [10, 99, 20, 88, 30]
4. Using Negative Indices
import numpy as np
arr = np.array([5, 10, 15])
# Insert 99 at the second-last position
new_arr = np.insert(arr, -1, 99)
# Resulting array: [5, 10, 99, 15]
Tips and Best Practices
- Performance considerations: Avoid excessive use on large arrays as
insert()
creates a new array each time, which can be computationally expensive. - Shape compatibility: Ensure the shape of
values
is compatible with the axis dimension when inserting along an axis to avoid errors. - Preallocation: For frequent additions, consider preallocating a larger array and using slicing for efficiency.
- Understand the axis parameter: Use the
axis
parameter wisely, as omitting it will flatten the array, potentially leading to unexpected results.