0

I have a levels array

#                  0    1    2    3   4
levels = np.array(( 0.2, 0.4, 0.6, 0.8 )) 

and a values array, e.g.,

np.random.seed(20230204)
values = np.random.rand(5)

and eventually a SLOW function

def map_into_levels(values, levels):
    result = []
    for n in np.asarray(values):
        for r, level in enumerate(levels):
            if n <= level:
                break
        else:
            r += 1
        result.append(r)
    return result

so that I have

In [153]: np.random.seed(20220204)
     ...: values = np.random.rand(6)
     ...: levels = np.array(( 0.2, 0.4, 0.6, 0.8 ))
     ...: result = map_into_levels(values, levels)
     ...: print(levels)
     ...: print(values)
     ...: print(result)
[0.2 0.4 0.6 0.8]
[0.00621839 0.23945242 0.87124946 0.56328486 0.5477085  0.88745812]
[0, 1, 4, 2, 2, 4]

In [154]:

Could you please point me towards a Numpy primitive that helps me to speed up the operations?

1
  • I'm not particularly happy with my title… I encourage you to edit it. Commented Feb 4, 2023 at 19:49

1 Answer 1

1

You need np.searchsorted assuming levels is sorted already. It find indices where elements should be inserted to maintain order:

np.searchsorted(levels, values)
# array([0, 1, 4, 2, 2, 4], dtype=int32)
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.