How to insert elements into ndarray
- insert() ==> inserting the element at the required position.
- append() ==> inserting the element at the end.
insert()
Example
Python
import numpy as np
help(np.insert)
Output
PowerShell
Help on function insert in module numpy:
insert(arr, obj, values, axis=None)
Insert values along the given axis before the given indices.
Example
Python
# insert(array, obj, values, axis=None)
# Insert values along the given axis before the given indices.
#obj-->Object that defines the index or indices before which 'values' are inserted.
#values--->Values to insert into array.
#axis ---->Axis along which to insert 'values' .
Output
PowerShell
output nhi h
1-D arrays
Example
Python
# To insert 7777 before index 2
a = np.arange(10)
b = np.insert(a,2,7777)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [0 1 7777 2 3 4 5 6 7 8 9]
Example
Python
# To insert 7777 before index 2 and 8888 before index 5?
a = np.arange(10)
b = np.insert(a,[2,5],[7777,8888])
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b :[ 0 1 7777 2 3 4 8888 5 6 7 8 9]
Example
Python
# To insert 7777 before index 2 and 8888 before index 5?
a = np.arange(10)
b = np.insert(a,[2,5],[7777,8888])
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [ 0 1 7777 2 3 4 7777 5 6 7 8 9]
Example
Python
# shape mismatch
a = np.arange(10)
b = np.insert(a,[2,5],[7777,8888,9999])
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-358-735011b8a30e> in <module>
1 # shape mismatch
2 a = np.arange(10)
----> 3 b = np.insert(a,[2,5],[7777,8888,9999])
4 print(f"array a : {a}")
5 print(f"array b : {b}")
<__array_function__ internals> in insert(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in insert(arr, obj, values, axis)
4676 slobj[axis] = indices
4677 slobj2[axis] = old_mask
-> 4678 new[tuple(slobj)] = values
4679 new[tuple(slobj2)] = arr
4680
ValueError: shape mismatch: value array of shape (3,) could not be broadcast to indexing resultof shape (2,)
Example
Python
# shape mismatch
a = np.arange(10)
b = np.insert(a,[2,5,7],[7777,8888])
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-359-d8cdd8c18d4d> in <module>
1 # shape mismatch
2 a = np.arange(10)
----> 3 b = np.insert(a,[2,5,7],[7777,8888])
4 print(f"array a : {a}")
5 print(f"array b : {b}")
<__array_function__ internals> in insert(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in insert(arr, obj, values, axis)
4676 slobj[axis] = indices
4677 slobj2[axis] = old_mask
-> 4678 new[tuple(slobj)] = values
4679 new[tuple(slobj2)] = arr
4680
ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (3,).
Example
Python
a = np.arange(10)
b = np.insert(a,[2,5,5],[777,888,999])
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [ 0 1 777 2 3 4 888 999 5 6 7 8 9]
Example
Python
# IndexError
a = np.arange(10)
b = np.insert(a,25,7777)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-361-423ff78357e9> in <module>
1 # IndexError
2 a = np.arange(10)
----> 3 b = np.insert(a,25,7777)
4 print(f"array a : {a}")
5 print(f"array b : {b}")
<__array_function__ internals> in insert(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in insert(arr, obj, values, axis)
4630 index = indices.item()
4631 if index < -N or index > N:
-> 4632 raise IndexError(
4633 "index %i is out of bounds for axis %i with "
4634 "size %i" % (obj, axis, N))
IndexError: index 25 is out of bounds for axis 0 with size 10
Note
- All the insertion points(indices) are identified at the beginning of the insert operation.
- Array should contain only homogeneous elements.
- By using insert() function, if we are trying to insert any other type element, then that element will be converted to array type automatically before insertion.
- If the conversion is not possible then we will get error.
Example
Python
# the original array contains int values. If inserted value is float then the float value
# is converted to the array type i.e., int. There may be data loss in this scenario
a = np.arange(10)
b = np.insert(a,2,123.456)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [ 0 1 123 2 3 4 5 6 7 8 9]
Example
Python
a = np.arange(10)
b = np.insert(a,2,True)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [0 1 1 2 3 4 5 6 7 8 9]
Example
Python
a = np.arange(10)
b = np.insert(a,2,'GK')
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-364-57774f62be41> in <module>
1 a = np.arange(10)
----> 2 b = np.insert(a,2,'GK')
3 print(f"array a : {a}")
4 print(f"array b : {b}")
<__array_function__ internals> in insert(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in insert(arr, obj, values, axis)
4638 # There are some object array corner cases here, but we canno
t avoid
4639 # that:
-> 4640 values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)
4641 if indices.ndim == 0
4642 # broadcasting is very different here, since a[:,0,:] =
.. behaves
ValueError: invalid literal for int() with base 10: 'GK'
Example
Python
a = np.arange(10)
b = np.insert(a,2,10+20j)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-365-d9aabac22b2c> in <module>
1 a = np.arange(10)
----> 2 b = np.insert(a,2,10+20j)
3 print(f"array a : {a}")
4 print(f"array b : {b}")
<__array_function__ internals> in insert(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in insert(arr, obj, values, axis)
4638 # There are some object array corner cases here, but we cannot avoid
4639 # that:
-> 4640 values = array(values, copy=False, ndmin=arr.ndim, dtype=arr.dtype)
4641 if indices.ndim == 0:
4642 # broadcasting is very different here, since a[:,0,:] =
.. behaves
TypeError: can't convert complex to int
Summary for 1-D arrays while insertion
- The number of indices and the number of elements should be matched.
- Out of range index is not allowed.
- Elements will be converted automatically to the array type.
2-D arrays
- If we are trying to insert elements into multi dimensional arrays, compulsory we have to provide axis.
- If we are not providing axis value, then default value None will be considered.
- In this case, array will be flatten to 1-D array and then insertion will be happend.
- axis=0 means rows (axis=-2).
- axis=1 means columns (axis=-1).
Example
Python
# if the axis is not defined for 2-D arrays, None is selected by default
# here the 2-D array flatten to 1-D array and insertion will be happened
a = np.array([[10,20],[30,40]])
b = np.insert(a,1,100)
print(f"array a :\n {a}")
print(f"array b : {b}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b : [ 10 100 20 30 40]
figar banana
Example
Python
# insert the elements along the axis=0 or axis=-2 ==> rows are inserted
a = np.array([[10,20],[30,40]])
b = np.insert(a,1,100,axis=0)
c = np.insert(a,1,100,axis=-2)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
print(f"array c :\n {c}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[ 10 20]
[100 100]
[ 30 40]]
array c :
[[ 10 20]
[100 100]
[ 30 40]]
Example
Python
# insert the elements along the axis=1 or axis=-1 ==> rows are inserted
a = np.array([[10,20],[30,40]])
b = np.insert(a,1,100,axis=1)
c = np.insert(a,1,100,axis=-1)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
print(f"array c :\n {c}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[ 10 100 20]
[ 30 100 40]]
array c :
[[ 10 100 20]
[ 30 100 40]]
Example
Python
# to insert multiple rows
a = np.array([[10,20],[30,40]])
b = np.insert(a,1,[[100,200],[300,400]],axis=0)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[ 10 20]
[100 200]
[300 400]
[ 30 40]]
Example
Python
# to insert multiple columns
a = np.array([[10,20],[30,40]])
b = np.insert(a,1,[[100,200],[300,400]],axis=1)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[ 10 100 300 20]
[ 30 200 400 40]]
Example
Python
# ValueError
a = np.array([[10,20],[30,40]])
b = np.insert(a,1,[100,200,300],axis=0)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-371-926c0e00dba4> in <module>
1 # ValueError
2 a = np.array([[10,20],[30,40]])
----> 3 b = np.insert(a,1,[100,200,300],axis=0)
4
5 print(f"array a :\n {a}")
<__array_function__ internals> in insert(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in insert(arr, obj, values, axis)
4650 new[tuple(slobj)] = arr[tuple(slobj)]
4651 slobj[axis] = slice(index, index+numnew)
-> 4652 new[tuple(slobj)] = values
4653 slobj[axis] = slice(index+numnew, None)
4654 slobj2 = [slice(None)] * ndim
ValueError: could not broadcast input array from shape (1,3) into shape (1,2)
append()
- By using insert() function, we can insert elements at our required index position.
- If we want to add elements always at end of the ndarray, then we have to go for append() function.
Example
Python
import numpy as np
help(np.append)
Output
PowerShell
Help on function append in module numpy:
append(arr, values, axis=None)
Append values to the end of an array.
1-D arrays
- If appended element type is not same type of array, then elements conversion will be happend such that all elements of same common type.
Example
Python
# append 100 element to the existing array of int
a = np.arange(10)
b = np.append(a,100)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [ 0 1 2 3 4 5 6 7 8 9 100]
Example
Python
# if the inserted element is not the type of the array then common type conversion
happened
a = np.arange(10)
b = np.append(a,20.5)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 20.5]
Example
Python
a = np.arange(10)
b = np.append(a,"GK")
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : ['0' '1' '2' '3' '4' '5' '6' '7' '8' '9' 'GK']
Example
Python
a = np.arange(10)
b = np.append(a,"GK")
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [0 1 2 3 4 5 6 7 8 9 1]
Example
Python
a = np.arange(10)
b = np.append(a,20+15j)
print(f"array a : {a}")
print(f"array b : {b}")
Output
PowerShell
array a : [0 1 2 3 4 5 6 7 8 9]
array b : [ 0. +0.j 1. +0.j 2. +0.j 3. +0.j 5. +0.j 5. +0.j 6. +0.j 7. +o.j 8. +0.j 9. +0.j 20.+15.j]
+0.j 8. +0.j 9. +0.j 20.+15.j]
2-D arrays
- If we are not specifying axis, then input array will be flatten to 1-D array and then append will be performed.
- If we are providing axis, then all the input arrays must have same number of dimensions, and same shape of provided axis.
- if axis-0 is taken then the obj should match with the number of columns of the input array.
- if axis-1 is taken then the obj should match with the number of rows of the input array.
Example
Python
# here axis is not specified so the default "None" will be taken and flatten to 1-D
array & insertion
a = np.array([[10,20],[30,40]])
b = np.append(a,70)
print(f"array a :\n {a}")
print(f"array b : {b}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b : [10 20 30 40 70]
Example
Python
# axis=0 ==> along rows
# Value Error : i/p array is 2-D and appended array is 0-D
a = np.array([[10,20],[30,40]])
b = np.append(a,70,axis=0) # appended is 0-D => 70
print(f"array a :\n {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)<ipython-input-379-c2af6bdb12eb> in<module>
2 # Value Error : i/p array is 2-D and appended array is 0-D
3 a = np.array([[10,20],[30,40]])
----> 4 b = np.append(a,70,axis=0) # appended is 0-D => 70
5 print(f"array a :\n {a}")
6 print(f"array b : {b}")
<__array_function__ internals> in append(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
4743 values = ravel(values)
4744 axis = arr.ndim-1
-> 4745 return concatenate((arr, values), axis=axis)
4746
4747
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input arrays must have same number of dimensions, butthe array at index 0 has 2 dimension(s) and the array at index 1 has 0dimension(s)
Example
Python
# Value Error : i/p array is 2-D and appended array is 1-D
a = np.array([[10,20],[30,40]])
b = np.append(a,[70,80],axis=0) # appended is 1-D => [70,80]
print(f"array a :\n {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-380-d1f0cddf5145> in <module>
1 # Value Error : i/p array is 2-D and appended array is 1-D
2 a = np.array([[10,20],[30,40]])
----> 3 b = np.append(a,[70,80],axis=0) # appended is 1-D => [70,80]
4 print(f"array a :\n {a}")
5 print(f"array b : {b}")
<__array_function__ internals> in append(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
4743 values = ravel(values)
4744 axis = arr.ndim-1
-> 4745 return concatenate((arr, values), axis=axis)
4746
4747
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 2 dimension(s) and the array at index 1 has dimension(s).
Example
Python
# i/p array is 2-D and appended array is 2-D
a = np.array([[10,20],[30,40]])
b = np.append(a,[[70,80]],axis=0) # appended is 2-D => [[70,80]]
# i/p array is 2-D and appended array is 2-D
a = np.array([[10,20],[30,40]])
b = np.append(a,[[70,80]],axis=0) # appended is 2-D => [[70,80]]
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[10 20]
[30 40]
[70 80]]
Example
Python
# axis=1 along colums
# Value Error : i/p array is Size 2 and appended element is size 1
a = np.array([[10,20],[30,40]])
b = np.append(a,[[70,80]],axis=1) # appended is size 1 => [[70,80]]
print(f"array a :\n {a}")
print(f"array b : {b}")
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-382-469d4a0f90ba> in <module>
2 # Value Error : i/p array is Size 2 and appended element is size 1
3 a = np.array([[10,20],[30,40]])
----> 4 b = np.append(a,[[70,80]],axis=1) # appended is size 1 => [[70,80]]
5 print(f"array a :\n {a}")
6 print(f"array b : {b}")
<__array_function__ internals> in append(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
4743 values = ravel(values)
4744 axis = arr.ndim-1
-> 4745 return concatenate((arr, values), axis=axis)
4746
4747
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 2 and the array at index 1 has size 1
Example
Python
a = np.array([[10,20],[30,40]])
b = np.append(a,[[70],[80]],axis=1)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[10 20 70]
[30 40 80]]
Example
Python
# multiple columns
a = np.array([[10,20],[30,40]])
b = np.append(a,[[70,80],[90,100]],axis=1)
print(f"array a :\n {a}")
print(f"array b :\n {b}")
Output
PowerShell
array a :
[[10 20]
[30 40]]
array b :
[[ 10 20 70 80]
[ 30 40 90 100]]
Example
Python
# Consider the array?
a = np.arange(12).reshape(4,3)
# Which of the following operations will be performed successfully?
# A. np.append(a,[[10,20,30]],axis=0) #valid
# B. np.append(a,[[10,20,30]],axis=1) #invalid
# C. np.append(a,[[10],[20],[30]],axis=0) #invalid
# D. np.append(a,[[10],[20],[30],[40]],axis=1) #valid
# E. np.append(a,[[10,20,30],[40,50,60]],axis=0) #valid
# F. np.append(a,[[10,20],[30,40],[50,60],[70,80]],axis=1) #valid
Output
PowerShell
output nhi h
Example
Python
np.append(a,[[10,20,30]],axis=0) #valid
Output
PowerShell
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[10, 20, 30]])
Example
Python
np.append(a,[[10,20,30]],axis=1) #invalid
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-387-4f71b3d245ce> in <module>
----> 1 np.append(a,[[10,20,30]],axis=1) #invalid
<__array_function__ internals> in append(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
4743 values = ravel(values)
4744 axis = arr.ndim-1
-> 4745 return concatenate((arr, values), axis=axis)
4746
4747
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 0, the array at index 0 has size 4 and the array at index 1 has size 1.
Example
Python
np.append(a,[[10],[20],[30]],axis=0) #invalid.
Output
PowerShell
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-388-52259d5553e8> in <module>
----> 1 np.append(a,[[10],[20],[30]],axis=0) #invalid
<__array_function__ internals> in append(*args, **kwargs)
F:\Users\Gopi\anaconda3\lib\site-packages\numpy\lib\function_base.py in append(arr, values, axis)
4743 values = ravel(values)
4744 axis = arr.ndim-1
-> 4745 return concatenate((arr, values), axis=axis)
4746
4747
<__array_function__ internals> in concatenate(*args, **kwargs)
ValueError: all the input array dimensions for the concatenation axis must match exactly, but along dimension 1, the array at index 0 has size 3 and the array at index 1 has size 1.
Example
Python
np.append(a,[[10],[20],[30],[40]],axis=1) #valid.
Output
PowerShell
array([[ 0, 1, 2, 10],
[ 3, 4, 5, 20],
[ 6, 7, 8, 30],
[ 9,10,11, 40]])
Example
Python
np.append(a,[[10,20,30],[40,50,60]],axis=0) #valid.
Output
PowerShell
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11],
[10, 20, 30],
[40, 50, 60]])
Example
Python
np.append(a,[[10,20],[30,40],[50,60],[70,80]],axis=1) #valid.
Output
PowerShell
array([[ 0, 1, 2, 10, 20],
[ 3, 4, 5, 30, 40],
[ 6, 7, 8, 50, 60],
[ 9, 10, 11, 70, 80]])
Example
Python
a = np.arange(12).reshape(4,3)
print(a)
b = np.append(a,[[10],[20],[30],[40]],axis=1)
print(b)
Output
PowerShell
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 0 1 2 10]
[ 3 4 5 20]
[ 6 7 8 30]
[ 9 10 11 4 0]]
Example
Python
a = np.arange(12).reshape(4,3)
print(a)
b = np.append(a,[[10,50],[20,60],[30,70],[40,80]],axis=1)
print(b)
Output
PowerShell
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
[[ 0 1 2 10 50]
[ 3 4 5 20 60]
[ 6 7 8 30 70]
[ 9 10 11 40 80]
insert() vs append()
- By using insert() function, we can insert elements at our required index position.
- But by using append() function, we can add elements always at the end of ndarray.