0

Consider the code

import numpy as np

v = np.linspace(0, 9, 10)
w = np.array([3.5, 4.5])
idx = np.searchsorted(v, w)
v = np.insert(v, idx, w)

print(idx, v[idx])

which outputs

[4 5] array([3.5, 4. ])

The variable idx contains the indices of the elements of w if they were inserted in v one by one. When inserting an array into another like above, only the value of idx corresponding to the minimum value of w will give as well the position of the same value into v.

Is there a way with numpy functions to obtain the indices of the elements of w once inserted?

8
  • What would be the expected output? Commented Jul 28, 2022 at 12:48
  • An automated way to obtain the indices of the values of w into v. A variable idx_new such that v[idx_new] == w is True element by element Commented Jul 28, 2022 at 12:49
  • Add 1 for each prior index Commented Jul 28, 2022 at 13:07
  • 1
    @G.Gare Doing searchsorted in the array after inserting the elements is worst than sorting the elements beforehand Commented Jul 28, 2022 at 13:09
  • 1
    No, because v has already w inserted Commented Jul 28, 2022 at 13:11

3 Answers 3

2

One solution:

import numpy as np

v = np.linspace(0, 9, 10)
w = np.array([3.5, 4.5])
idx = np.searchsorted(v, w)
v = np.insert(v, idx, w)

new_idx = idx + np.arange(len(idx))
print(new_idx, v[new_idx])

Output

[4 5] [3.5 4.5]
Sign up to request clarification or add additional context in comments.

10 Comments

doesn't work if w is not sorted
@G.Gare Why don't sort w then?
if w has a million entries you may want to avoid that, but it's a good solution nevertheless!
You need to apply the argsort of the argsort of the index to the range for a general solution
This answer is the best if the vector w is sorted, or with a pre-sorting of w
|
2

Perhaps the most elegant solution is

idx_new = idx + np.argsort(np.argsort(idx))

but probably not the fastest

1 Comment

This is the second to most elegant solution :) Most elegant is pre-sorting the data to begin with, since that only requires one sort instead of 2
1

I tried this, I hope it is general enough

import numpy as np
v = np.linspace(0, 9, 10)
w = np.array([3.5, 4.5])
idx = np.searchsorted(v, w)
v = np.insert(v, idx, w)

print(idx, v[idx])
idx_new = np.searchsorted(v, w)
print(idx_new)
print(v[idx_new], w)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.