Given an a numpy array of size n
and an integer m
I want to generate all sequential m
length subsequences of the array, preferably as a two dimensional array.
Example:
>>> subsequences(arange(10), 4)
array([[0, 1, 2, 3, 4, 5, 6],
[1, 2, 3, 4, 5, 6, 7],
[2, 3, 4, 5, 6, 7, 8],
[3, 4, 5, 6, 7, 8, 9]])
the best way I can come up with to do this is
def subsequences(arr, m):
n = arr.size
# Create array of indices, essentially solution for "arange" input
indices = cumsum(vstack((arange(n - m + 1), ones((m-1, n - m + 1), int))), 0)
return arr[indices]
Is there a better, preferably built in, function that I'm missing?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…