Nickpick
Nickpick

Reputation: 6597

Numpy operation of arrays with different size

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.

Upvotes: 2

Views: 367

Answers (1)

Divakar
Divakar

Reputation: 221654

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)

Upvotes: 3

Related Questions