Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

NumPy: insert() function

numpy.insert() function

The insert() function is used to insert values along the given axis before the given indices.

Syntax:

numpy.insert(arr, obj, values, axis=None)
NumPy manipulation: insert() function

Version: 1.15.0

Parameter:

Name Description Required /
Optional
arr Input array. Required
obj Object that defines the index or indices before which values is inserted.
Support for multiple insertions when obj is a single scalar or a sequence with one element (similar to calling insert multiple times).
Required
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 Optional
axis Axis along which to insert values. If axis is None then arr is flattened first. Optional

Return value:

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.

Example-1: numpy.insert()

>>> import numpy as np
>>> x = np.array([[0,0], [1,1], [2,2]])
>>> x
array([[0, 0],
       [1, 1],
       [2, 2]])
>>> np.insert(x, 2, 4)
array([0, 0, 4, 1, 1, 2, 2])
>>> np.insert(x, 2, 4, axis=1)
array([[0, 0, 4],
       [1, 1, 4],
       [2, 2, 4]])

Pictorial Presentation:

NumPy manipulation: insert() function

Example-2: numpy.insert()

>>> import numpy as np
>>> x = np.array([[0,0], [1,1], [2,2]])
>>> np.insert(x, [1], [[3], [4], [5]], axis=1) 
array([[0, 3, 0],
       [1, 4, 1],
       [2, 5, 2]])
>>> np.array_equal(np.insert(x, 1, [3, 4, 5], axis=1), np.insert(x, [1], [[3], [4], [5]], axis=1))
True

Pictorial Presentation:

NumPy manipulation: insert() function

Example-3: numpy.insert()

>>> import numpy as np
>>> x = np.array([[0,0], [1,1], [2,2]])
>>> y = x.flatten()
>>> y
array([0, 0, 1, 1, 2, 2])
>>> np.insert(y, [3,3], [6,7])
array([0, 0, 1, 6, 7, 1, 2, 2])
>>> np.insert(y, slice(3,5),[7,8])
array([0, 0, 1, 7, 1, 8, 2, 2])
>>> np.insert(y, [3,3], [8.12, False])
array([0, 0, 1, 8, 0, 1, 2, 2])

Example-4: numpy.insert()


>>> import numpy as np
>>> z = np.arange(12).reshape(3,4)
>>> idz = (1, 3)
>>> np.insert(z, idz, 777, axis=1)
array([[  0, 777,   1,   2, 777,   3],
       [  4, 777,   5,   6, 777,   7],
       [  8, 777,   9,  10, 777,  11]])

Pictorial Presentation:

NumPy manipulation: insert() function

Python - NumPy Code Editor:

Previous: delete()
Next: append()