NumPy insert()

The insert() method adds the values along the given axis at specified indices.

Here, the insert() method inserted a new item 4 to the index 2, and shifted the previous item to the next index.


insert() Syntax

The syntax of insert() is:

numpy.insert(array, obj, values, axis)

insert() Arguments

The insert() method takes four arguments:

  • array - original array
  • obj - indices at which values are inserted
  • values - the array to be inserted at the given position
  • axis(optional) - the axis along which the values are inserted

insert() Return Value

The insert() method returns an array with values inserted.


Example 1: Insert an Array at Given Index

Output

[0 1 4 5 6 7 2 3]

Example 2: Insert an Array Element at Different Indices

We can insert different values at different indices.

Output

[0 7 1 4 6 2 5 3]

Note: When passing a sequence as obj, the size of the sequence should match the size of the values. For example, when inserting 4 values, 4 indices should be provided.


Example 3: Insert into a 2-D Array Before Given Index

Similar to a 1-D array, values can be inserted to a 2-D array at any index along any axis.

Output

Insert to 2D array at index 2
[0 1 4 5 2 3]

Insert to 2D array at row 2
 [[0 1]
 [2 3]
 [4 5]]

Insert to 2D array at column 2
[[0 1 4]
 [2 3 5]]

Note: If the axis is not provided, the array is flattened.


Example 3: Insert into a 2-D array Before Given Indices

Output

Insert to 2D array before indices 0 and 1
[4 0 5 1 2 3]
Insert to 2D array before row 0 and row 1 along axis 0
 [[4 5]
 [0 1]
 [4 5]
 [2 3]]

Insert to 2D array before column 0 and column 1 along axis 1
[[4 0 5 1]
 [4 2 5 3]]