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)
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:
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:
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:
Python - NumPy Code Editor:
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework