Skip to content Skip to sidebar Skip to footer

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:

  1. (a-a[0])/thresh does integer division (assuming a has an integer dtype) to bin the values into groups thresh wide.

  2. cumsum(bincount(...)) counts the size of each group and converts them into indices. Note that if there's no values in a bucket bincount will report 0, so there may be repeats in this array.

  3. 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"