1

If I have an array x, an array of start indices s, and a distance d, how do I create an array y, s.t. y[i] == x[s[i]:s[i]+d]?

michaelsnowden
  • 6,031
  • 2
  • 38
  • 83

2 Answers2

1

You can create a strided view of a sliding d-window into x and then use advanced indexing:

>>> x = np.random.randint(0, 10, (20,))
>>> d = 4
>>> s = np.random.randint(0, 17, (10,))
>>> 
>>> x
array([2, 4, 5, 6, 6, 4, 8, 2, 6, 6, 0, 2, 8, 3, 5, 1, 6, 2, 9, 8])
>>> s
array([16,  4,  6,  0, 16,  1, 14,  4,  6,  6])
>>> 
>>> assert x.ndim == 1
>>> assert x.flags.contiguous
>>>
>>> xx  = np.lib.stride_tricks.as_strided(x, (x.size-d+1, d), 2*x.strides)
>>> y = xx[s]
>>> y
array([[6, 2, 9, 8],
       [6, 4, 8, 2],
       [8, 2, 6, 6],
       [2, 4, 5, 6],
       [6, 2, 9, 8],
       [4, 5, 6, 6],
       [5, 1, 6, 2],
       [6, 4, 8, 2],
       [8, 2, 6, 6],
       [8, 2, 6, 6]])
Paul Panzer
  • 51,835
  • 3
  • 54
  • 99
0

Not sure if this is the best way, but you can use tuple indexing:

x[np.stack((s,s+d))]
michaelsnowden
  • 6,031
  • 2
  • 38
  • 83