We can add values at the given index position of a Numpy array by using append().
numpy.insert(arr,obj, values, axis=None)
arr : Values are added to the copy of this array. obj : index or indices before which the value will be added. values : Values to be added to arr. Must be of same shape of the arr ( if Axis is present ). If Axis is not specified then matching shape of arr is not prerequisite. axis : (Optional) Direction in which the values to be appended. Arrays are flattened before insert() if axis is not given.
Note that there is no change to the original array.
import numpy as np
npr=np.array([5,8,3])
npr1=np.insert(npr,1,10) # adding value ( 10 ) at index position 1
print(npr) # [5 8 3] , No change to original array
print(npr1)# [ 5 10 8 3], element added at 2nd position
import numpy as np
npr=np.array([5,8,3])
npr1=np.insert(npr,len(npr),10) # adding at the end
print(npr) # [5 8 3] , No change to original array
print(npr1) # [ 5 8 3 10] , 10 added at the end
if Axis is provided then adding array or values must have same shape of the original array. In case of any mismatch we will get this error message. ValueError: could not broadcast input array from shape (1,5) into shape (1,4)
If axis is not given then the arrays are flattened before inserting.
import numpy as np
npr=np.array([[0,1,2,4],
[3,4,5,6],
[6,7,8,9]])
npr1=np.insert(npr,1,[10,11,12])
print(npr1)
Output
[ 0 10 11 12 1 2 4 3 4 5 6 6 7 8 9]
By using reshape() we can match the requirements of insert ( to match the shape ) and then use.
import numpy as np
npr=np.array([[0,1,2,4],[3,4,5,6],[6,7,8,9]])
npr1=np.array([10,11,12,13,21,22,23,24,31,32,34,35]) # different shape
#npr1=npr1.reshape(3,4)
npr1=npr1.reshape(npr.shape) # Match the shape of first array
npr2=np.insert(npr,2,npr1,axis=0)
print(npr2)
Adding one element in each row. Note how the shape is matched.
import numpy as np
npr=np.array([[0,1,2,4],[3,4,5,6],[6,7,8,9]])
npr1=np.array([[10],[11],[12]]) # One element for each row
npr2=np.insert(npr,[3,2,1],npr1,axis=1)
print(npr2)