Skip to content Skip to sidebar Skip to footer

Number Of Elements Of Numpy Arrays Inside Specific Bins

I have an ensemble of sorted (one-dimensional) arrays of unequal lengths (say M0, M1 and M2). I want to find how many elements of each of these arrays is inside specific number ran

Solution 1:

We could make use of the sorted nature and hence use np.searchsorted for this task, like so -

out = np.empty((len(zbin)-1, len(lst)),dtype=int)
for i,l inenumerate(lst):
    left_idx = np.searchsorted(l, zbin[:-1], 'left')
    right_idx = np.searchsorted(l, zbin[1:], 'right')
    out[:,i] = right_idx - left_idx

Solution 2:

I would guess it would be difficult to beat the performance of simply looping over each array and calling numpy.histogram. I’m guessing you haven’t tried this or you’d have mentioned it!

It’s certainly possible that you could exploit the sorted nature to come up with a faster solution, but I’d start by comparing the timing of that.

Post a Comment for "Number Of Elements Of Numpy Arrays Inside Specific Bins"