numpy.insert#

numpy.insert(arr,obj,values,axis=None)[source]#

Insert values along the given axis before the given indices.

Parameters:
arrarray_like

Input array.

objslice, int, array-like of ints or bools

Object that defines the index or indices before whichvalues isinserted.

Changed in version 2.1.2:Boolean indices are now treated as a mask of elements to insert,rather than being cast to the integers 0 and 1.

Support for multiple insertions whenobj is a single scalar or asequence with one element (similar to calling insert multipletimes).

valuesarray_like

Values to insert intoarr. If the type ofvalues is differentfrom that ofarr,values is converted to the type ofarr.values should be shaped so thatarr[...,obj,...]=valuesis legal.

axisint, optional

Axis along which to insertvalues. Ifaxis is None thenarris flattened first.

Returns:
outndarray

A copy ofarr withvalues inserted. Note thatinsertdoes not occur in-place: a new array is returned. Ifaxis is None,out is a flattened array.

See also

append

Append elements at the end of an array.

concatenate

Join a sequence of arrays along an existing axis.

delete

Delete elements from an array.

Notes

Note that for higher dimensional insertsobj=0 behaves very differentfromobj=[0] just likearr[:,0,:]=values is different fromarr[:,[0],:]=values. This is because of the difference between basicand advancedindexing.

Examples

>>>importnumpyasnp>>>a=np.arange(6).reshape(3,2)>>>aarray([[0, 1],       [2, 3],       [4, 5]])>>>np.insert(a,1,6)array([0, 6, 1, 2, 3, 4, 5])>>>np.insert(a,1,6,axis=1)array([[0, 6, 1],       [2, 6, 3],       [4, 6, 5]])

Difference between sequence and scalars,showing howobj=[1] behaves different fromobj=1:

>>>np.insert(a,[1],[[7],[8],[9]],axis=1)array([[0, 7, 1],       [2, 8, 3],       [4, 9, 5]])>>>np.insert(a,1,[[7],[8],[9]],axis=1)array([[0, 7, 8, 9, 1],       [2, 7, 8, 9, 3],       [4, 7, 8, 9, 5]])>>>np.array_equal(np.insert(a,1,[7,8,9],axis=1),...np.insert(a,[1],[[7],[8],[9]],axis=1))True
>>>b=a.flatten()>>>barray([0, 1, 2, 3, 4, 5])>>>np.insert(b,[2,2],[6,7])array([0, 1, 6, 7, 2, 3, 4, 5])
>>>np.insert(b,slice(2,4),[7,8])array([0, 1, 7, 2, 8, 3, 4, 5])
>>>np.insert(b,[2,2],[7.13,False])# type castingarray([0, 1, 7, 0, 2, 3, 4, 5])
>>>x=np.arange(8).reshape(2,4)>>>idx=(1,3)>>>np.insert(x,idx,999,axis=1)array([[  0, 999,   1,   2, 999,   3],       [  4, 999,   5,   6, 999,   7]])
On this page