How to insert values to a given array in NumPy

Overview

The insert() function in Python is used to insert values along the given axis of an array before the given index position.

Syntax

The insert() function has the following syntax:

numpy.insert(arr, obj, values, axis=None)
Syntax for the insert() function in Python

Parameters

The insert() function takes the following parameters:

  • arr: This is the input array. It is a required parameter.
  • obj: This is the object that specifies the index position before which the values are inserted into the input array. It is a required parameter.
  • values: This represents the values to be inserted into the input array. It is a required parameter.
  • axis: This is the axis along which the values are inserted. It is an optional parameter.

Return value

The insert() function returns a copy of the input array but with new values inserted into it.

Example

import numpy as np
# creating an input array
a = np.arange(9).reshape(3,3)
# calling the insert() function
my_array = np.insert(a, 1, [10, 11, 12], axis = 0 )
# printing the old array
print("This is th input array", a)
# printing the new array
print("This is the new array", my_array)

Example

  • Line 1: We import the numpy module.
  • Line 3: We create an input array, a.
  • Line 6: We call the insert() function on the array, a, and assign the result to a variable, my_array.
  • Line 9: We print the input array, a.
  • Line 12: We print the new array, my_array.

Free Resources