2
c=np.array([ 0.  ,  0.2,  0.22,  0.89,  0.99])
rnd = np.random.uniform(low=0.00, high=1.00, size=12)

I want to see how many elements in c are smaller than each of the 12 random numbers in rnd. It needs to be in numpy and without the use of any lists so that it's faster.

The output will be an array of 12 elements, each describing how many elements for each of them are small than the corresponding number in rnd.

1
  • please edit your question with an example of expected output Commented Feb 20, 2016 at 10:53

1 Answer 1

3

You can use broadcasting after extending c from 1D to a 2D array verison with None/np.newaxis for performing comparisons on all elements in a vectorized manner and then summing along rows with .sum(0) for the counting, like so -

(c[:,None] < rnd).sum(0)

It seems you can also use the efficient np.searchsorted like so -

np.searchsorted(c,rnd)
Sign up to request clarification or add additional context in comments.

6 Comments

Yes that looks great. What's the 'None' stand for?
Ok, a little follow up question. If the result of your output is then the index for the original c, how can I get the numbers = rnd[(c[:,None] < rnd).sum(0)]. Do I need broadcasting again?
The result is a count not an index. What exactly do you have in mind? I don't think I understood this follow-up question. Could you elaborate?
yes the count will then be used as an index, you understood correctly. In fact the count-1
Yes but c has 5 elements while count has 12
|

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.