Speed Up Comparison Of Floats Between Lists
I have a block of code which does the following: take a float from a list, b_lst below, of index indx check if this float is located between a float of index i and the next one (o
Solution 1:
You want to take a look at numpy's searchsorted
. Calling
np.searchsorted(a_lst, b_lst, side='right')
will return an array of indices, the same length as b_lst
, holding before which item in a_lst
they should be inserted to preserve order. It will be very fast, as it uses binary search and the looping happens in C. You could then create your subarrays with fancy indexing, e.g.:
>>>a = np.arange(1, 10)>>>b = np.random.rand(100) * 10>>>c = np.searchsorted(a, b, side='right')>>>b[c == 0]
array([ 0.54620226, 0.40043875, 0.62398925, 0.40097674, 0.58765603,
0.14045264, 0.16990249, 0.78264088, 0.51507254, 0.31808327,
0.03895417, 0.92130027])
>>>b[c == 1]
array([ 1.34599709, 1.42645778, 1.13025996, 1.20096723, 1.75724448,
1.87447058, 1.23422399, 1.37807553, 1.64118058, 1.53740299])
Post a Comment for "Speed Up Comparison Of Floats Between Lists"