Skip to content Skip to sidebar Skip to footer

How To Vectorize With Numpy.searchsorted In A 2d-array

I have a 2d-array (a) for lookup and an array (v) to find indices where elements should be inserted: import numpy as np # [EDIT] Add more records which contain NaNs a = np.array(

Solution 1:

Inspired by Vectorized searchsorted numpy for the underlying idea, here's one between 2D and 1D arrays -

defsearchsorted2d(a,b):
    # Inputs : a is (m,n) 2D array and b is (m,) 1D array.# Finds np.searchsorted(a[i], b[i])) in a vectorized way by# scaling/offsetting both inputs and then using searchsorted# Get scaling offset and then scale inputs
    s = np.r_[0,(np.maximum(a.max(1)-a.min(1)+1,b)+1).cumsum()[:-1]]
    a_scaled = (a+s[:,None]).ravel()
    b_scaled = b+s

    # Use searchsorted on scaled ones and then subtract offsetsreturn np.searchsorted(a_scaled,b_scaled)-np.arange(len(s))*a.shape[1]

Output on given sample -

In [101]: searchsorted2d(a,v)
Out[101]: array([ 1,  9, 10,  6,  9])

Case with all NaNs rows

To extend to make it work for all NaNs rows, we need few more steps -

valid_mask =~np.isnan(a).any(1)
out= np.zeros(len(a), dtype=int)
out[valid_mask] = searchsorted2d(a[valid_mask],v[valid_mask])

Post a Comment for "How To Vectorize With Numpy.searchsorted In A 2d-array"