numpy.insert() function with example in python

Spread the love

numpy.insert(): This function insert values along the given axis before the given indices.

Syntax: numpy.insert(arr, obj, values, axis=None)

arr : array_like
Input array.

obj : int, slice or sequence of ints
Object that defines the index or indices before which values is inserted.

New in version 1.8.0.

Support for multiple insertions when obj is a single scalar or a sequence with one element (similar to calling insert multiple times).

values : array_like
Values to insert into arr. If the type of values is different from that of arr, values is converted to the type of arr. values should be shaped so that arr[…,obj,…] = values is legal.

axis : int, optional
Axis along which to insert values. If axis is None then arr is flattened first.

out : ndarray
A copy of arr with values inserted. Note that insert does not occur in-place: a new array is returned. If axis is None, out is a flattened array.

import numpy as np import numpy as np a= np.array([[1,2],[2,3],[3,4]]) b=np.insert(a,5,6) print(b) c=np.insert(a, 1, 5, axis=1) print("with axis 1",c)


[1 2 2 3 3 6 4]

with axis 1  [[1 5 2]
[2 5 3]
[3 5 4]]



Leave a Reply

Your email address will not be published. Required fields are marked *