Better way to insert elements into numpy array
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?
1 Answer
Use rangeoffsetted 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])
Divakar
posted this
Have an answer?
JD
You probably shouldn't be doing this. It's more efficient to work with Python lists if they're changing size