Better way to insert elements into numpy array

2302 views python
7

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?

answered question

You probably shouldn't be doing this. It's more efficient to work with Python lists if they're changing size

The complication is with your choice of indices - are they relative to the original array or the target. insert put the 2 after original[1], and 4 after original[3]. You in contrast want them to be at the result[1] and result[3] slots.

1 Answer

6

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])

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories