I have a numpy array and I have a list of elements I want to insert at specific locations (not contiguous) into that array. The indices are in another numpy array.
target answer: [1,2,3,4,5]
original array: [1,3,5]
elements to insert: [2,4]
indices: [1,3]
numpy.insert(arr,[1,3],[2,4])
dosen't give the desired result. It gives [1,2,3,5,4]
.
Any pointers?
Use range-offsetted indices with np.insert
-
np.insert(a, add_idx - np.arange(len(add_idx)), add_val)
Sample run -
In [20]: a
Out[20]: array([1, 3, 5])
In [21]: add_idx
Out[21]: [1, 3]
In [22]: add_val
Out[22]: [2, 4]
In [23]: np.insert(a, add_idx - np.arange(len(add_idx)), add_val)
Out[23]: array([1, 2, 3, 4, 5])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With