Home > Mobile >  Advanced slicing over 1D numpy array
Advanced slicing over 1D numpy array

Time:11-21

Is it possible to apply few conditions to numpy.array while indexing them? In my case I want to show first 10 elements and then 2 neighbour elements with step 5:

numpy.arange(40)

#Output is:
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16,
       17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33,
       34, 35, 36, 37, 38, 39])

Applying my conditions to this array I want to get this:

array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 14, 15, 20, 21, 26, 27, 32,
       33, 38, 39])

I haven't found any solution. I thought it should look something like this:

np.arange(40)[0:10, 10:len(np.arange(40)):5]

But it's not working for me.

CodePudding user response:

You can try custom indexing on reshaped array:

n = 40
idx = np.zeros(n//2, dtype=bool)
idx[:5] = True
idx[4:None:3] = True
>>> np.arange(n).reshape(-1,2)[idx]
array([[ 0,  1],
       [ 2,  3],
       [ 4,  5],
       [ 6,  7],
       [ 8,  9],
       [14, 15],
       [20, 21],
       [26, 27],
       [32, 33],
       [38, 39]])
>>> np.arange(n).reshape(-1,2)[idx].ravel()
array([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 14, 15, 20, 21, 26, 27, 32,
       33, 38, 39])
  • Related