Numpy - Selecting Elements From An Array With Spacing
I have a numpy array with a bunch of monotonically increasing values. Say, a = [1,2,3,4,6,10,10,11,14] a_arr=np.array(a) Also say thresh = 4 I want to create an array that conta
Solution 1:
Here's a vectorized solution to your approximate problem:
idx = np.cumsum(np.bincount((a-a[0])/thresh))[:-1]
This gives you all the indices except for the first zero, which is always present. Here's the explanation:
(a-a[0])/thresh
does integer division (assuminga
has an integer dtype) to bin the values into groupsthresh
wide.cumsum(bincount(...))
counts the size of each group and converts them into indices. Note that if there's no values in a bucketbincount
will report 0, so there may be repeats in this array.Finally, we discard the last index, which corresponds to the size of
a
. Alternatively, if the order of indices doesn't matter, you could exploit this to get your zero index back:idx = np.cumsum(np.bincount((a-a[0])/thresh)) % len(a)
Post a Comment for "Numpy - Selecting Elements From An Array With Spacing"