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]
?
Asked
Active
Viewed 53 times
1

michaelsnowden
- 6,031
- 2
- 38
- 83
-
@zipzit Not homework, actual work lol – michaelsnowden Apr 19 '18 at 02:07
-
https://stackoverflow.com/questions/509211/understanding-pythons-slice-notation `y= x[s:s+d].copy()` . ewwww.. not quite sure this is what you want. How many i values are there? – zipzit Apr 19 '18 at 02:14
-
I'm pretty sure this is a dupe but can't find it right now. – Paul Panzer Apr 19 '18 at 02:50
2 Answers
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