Home > Mobile >  numpy invert stride selection
numpy invert stride selection

Time:12-20

Consider the following code:

aa = np.arange(16)
step = 4
bb = aa[::4]

This selects every 4th element. Is there a quick and easy numpy function to select the complement of bb? I'm looking for the following output

array([1,  2,  3, 5,  6,  7,  9, 10, 11, 13, 14, 15])

Yes, I could generate indices and then do np.setdiff1d, but I'm looking for something more elegant than that.

CodePudding user response:

If you're looking for a simple single-liner:

np.delete(aa,slice(None,None,4))

Another solution (I don't know about elegant), but you could define a selection index of ones, and then set every fourth element to False to then index the original array:

o = np.ones_like(s,dtype=bool)
o[::step] = False 
aa[o]

CodePudding user response:

A flexible way to select based on an arbitrary repeated position could be to use a modulo:

bb = aa[np.arange(len(aa))%step != step-1]

Output:

array([ 0,  1,  2,  4,  5,  6,  8,  9, 10, 12, 13, 14])
  • Related