5

I have two array my_arr and distances. For example:

my_arr= np.array([0, 1, 3, 4, 5, 3, 5])
distances = np.array([18, 47, 20, 10, 26, 22, 13])

I would like to get an array of indices whose shape is np.unique(my_arr).size based on the minimum distance. So in the previous example, I would get:

# indices of my_arr
indices_of_my_arr= np.array([0, 1, 2, 3, 6])

Except for loops or map is there a clever way to do this?

EDIT: Another example:

my_arr = np.array([0, 2, 3, 1, 3, 4, 4, 5])
dist = np.array([10, 12, 15, 18, 5, 14, 45, 8])

I expect:

[0, 1, 3, 4, 5, 7]

1 Answer 1

4

You can use np.lexsort and np.unique -

idx = np.lexsort([distances, my_arr])
out = np.sort(idx[np.unique(my_arr[idx], return_index=1)[1]])
Sign up to request clarification or add additional context in comments.

2 Comments

I have added another example because your solution does not yield the expected array.
@floflo29 Had to add in sort there. Check out the edit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.