In this chapter, we will discuss about NumPy- insert. This function inserts values in the input array along the given axis and before the given index. If the type of values is converted to be inserted, it is different from the input array. Insertion is not done in place and the function returns a new array. Also, if the axis is not mentioned, the input array is flattened.
The insert() function takes the following parameters −
numpy.insert(arr, obj, values, axis)
Where,
Sr.No. | Parameter & Description |
---|---|
1 | arrInput array |
2 | obj index before which insertion is to be made |
3 | valuesThe array of values to be inserted |
4 | axisThe axis along which to insert. If not given, the input array is flattened |
Example Of NumPy insert
import numpy as np a = np.array([[1,2],[3,4],[5,6]]) print 'First array:' print a print '\n' print 'Axis parameter not passed. The input array is flattened before insertion.' print np.insert(a,3,[11,12]) print '\n' print 'Axis parameter passed. The values array is broadcast to match input array.' print 'Broadcast along axis 0:' print np.insert(a,1,[11],axis = 0) print '\n' print 'Broadcast along axis 1:' print np.insert(a,1,11,axis = 1)
Its output would be as follows −
First array: [[1 2] [3 4] [5 6]] Axis parameter not passed. The input array is flattened before insertion. [ 1 2 3 11 12 4 5 6] Axis parameter passed. The values array is broadcast to match input array. Broadcast along axis 0: [[ 1 2] [11 11] [ 3 4] [ 5 6]] Broadcast along axis 1: [[ 1 11 2] [ 3 11 4] [ 5 11 6]]
Next Topic – Click Here
Pingback: NumPy Array Manipulation - Adglob Infosystem Pvt Ltd
Pingback: NumPy - append - Adglob Infosystem Pvt Ltd