Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 666
Karan_Saxena Avatar asked Oct 15 '25 09:10

Karan_Saxena


1 Answers

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])
like image 129
Divakar Avatar answered Oct 16 '25 22:10

Divakar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!