Let's say I have a 1D array of data. I want to (efficiently) produce an matrix, such that each row of the matrix is a contiguous range of values in the data array, and each row of the matrix is offset (in the original data array) by 1, with respect to the previous row.
This example will probably make that a little easier to understand:
# fake data, for demonstration
data = np.arange(100)
# some parameters
offset = 4
span = 10
n = 20
# one way to do this, I'm guessing the for loop is not the most efficient
np.stack([data[i+offset:i+offset+span] for i in range(n)])
Which produces:
array([[ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
[ 5, 6, 7, 8, 9, 10, 11, 12, 13, 14],
[ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[ 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
[ 8, 9, 10, 11, 12, 13, 14, 15, 16, 17],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18],
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
[12, 13, 14, 15, 16, 17, 18, 19, 20, 21],
[13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
[14, 15, 16, 17, 18, 19, 20, 21, 22, 23],
[15, 16, 17, 18, 19, 20, 21, 22, 23, 24],
[16, 17, 18, 19, 20, 21, 22, 23, 24, 25],
[17, 18, 19, 20, 21, 22, 23, 24, 25, 26],
[18, 19, 20, 21, 22, 23, 24, 25, 26, 27],
[19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
[21, 22, 23, 24, 25, 26, 27, 28, 29, 30],
[22, 23, 24, 25, 26, 27, 28, 29, 30, 31],
[23, 24, 25, 26, 27, 28, 29, 30, 31, 32]])
I've obviously already figured out how to do this, but I think that there must be a more efficient numpythonic way to do it that avoids the for-loop/stack. I'm going to need to do this a lot (in another loop) and would like to maximize the performance.
TIA