VOOZH about

URL: https://www.geeksforgeeks.org/python/numpy-insert-python/

⇱ numpy.insert() in Python - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

numpy.insert() in Python

Last Updated : 28 Mar, 2022

The numpy.insert() function inserts values along the mentioned axis before the given indices. Syntax : 

numpy.insert(array, object, values, axis = None)

Parameters : 

array : [array_like]Input array. 
object : [int, array of ints]Sub-array with the index or indices before 
 which values is inserted
values : [array_like]values to be added in the arr. Values should be 
 shaped so that arr[...,obj,...] = values. If the type of values is different from 
 that of arr, values is converted to the type of arr
axis : Axis along which we want to insert the values. By default, it 
 object is applied to flattened array 

Return : 

An copy of array with values being inserted as per the mentioned object along a given axis. 

Code 1 : Deletion from 1D array 

Output : 

1D arr : 
 [0 1 2 3 4]
Shape : (5,)

Array after insertion : [0 9 1 2 3 4]
Shape : (6,)


2D arr : 
 [[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
Shape : (3, 4)

Array after insertion : 
 [[ 0 9 1 2 3]
 [ 4 9 5 6 7]
 [ 8 9 9 10 11]]
Shape : (3, 5)

Code 2 : Working with Scalars 

Output : 

2D arr : 
 [[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
Shape : (3, 4)

Array after insertion : 
 [[ 0 1 2 3]
 [ 6 6 6 6]
 [ 9 9 9 9]
 [ 4 5 6 7]
 [ 8 9 10 11]]
Shape : (5, 4)

Array after insertion : 
 [[ 0 8 1 2 3]
 [ 4 7 5 6 7]
 [ 8 9 9 10 11]]
Shape : (3, 5)

Code 3 : Insertion at different points 

Output : 

1D arr : 
 [[0 1 2]
 [3 4 5]]
Shape : (2, 3)

Insertion at two points : [0 1 9 2 3 9 4 5]
Shape : (8,)


2D arr : 
 [[ 0 1 2 3]
 [ 4 5 6 7]
 [ 8 9 10 11]]
Shape : (3, 4)

Insertion at two points : 
 [[66 0 1 2 66 3]
 [66 4 5 6 66 7]
 [66 8 9 10 66 11]]
Shape : (3, 6)

References : https://numpy.org/doc/stable/reference/generated/numpy.insert.html#numpy.insert Note : These codes won’t run on online IDE's. Please run them on your systems to explore the working.

Comment