2

Given some data

In [1]: import numpy as np
In [2]: x = np.array(['a', 'b', 'b', 'a'])

And a sorted index

In [3]: i = np.array(['a', 'b'])

I want to find the location of each data entry within the index

In [4]: # solution here
array([0, 1, 1, 0])

This is a bit like categoricals. I don't want to use Pandas here. I want to do this on fixed length strings. I need this to be somewhat efficient.

1 Answer 1

5

You could use np.searchsorted:

>>> np.searchsorted(i, x)
array([0, 1, 1, 0])

The function finds out the index at which each element of x should be placed in i in order to maintain sorted order.

Sign up to request clarification or add additional context in comments.

Comments

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.