In case x is some data, like words or random values and we need to recombine it we could use reindexing mechanism in numpy.
Substituted by zero version
x = np.array([1,2,3,4])
wz = 2
zero = 0
Lets build indexing matrix.
ri = np.arange(-wz,wz+1)+np.arange(x.shape[0]).reshape(-1,1)
print(ri)
Output:
[[-2, -1, 0, 1, 2],
[-1, 0, 1, 2, 3],
[ 0, 1, 2, 3, 4],
[ 1, 2, 3, 4, 5]
Now if we add zero to x as last element we can replace wrong indexes with it index.
np.place(ri,(ri<0)|(ri>x.shape[0]),x.shape[0]) #replace wrong indexes
np.vstack((
np.hstack((x,[zero]))[ri].reshape(1,-1),#extending x with zero and reindexing
np.tile(x,2*wz+1)) #repeating basic `x` to each window position
)#.T #uncomment .T to make it vertical
Output:
([[0, 0, 1, 2, 3, 0, 1, 2, 3, 4, 1, 2, 3, 4, 0, 2, 3, 4, 0, 0],
[1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]])
Skipped version
The same idea, but in a slightly different order: produce a complete indexing matrix [window_index,x_index] then exclude the wrong pairs, and finally re-indexing 'x'.
x = np.array([1,2,3,4])
wz = 2
ri = np.vstack((
(np.arange(-wz,wz+1)+np.arange(x.shape[0]).reshape(-1,1)).ravel(),#same index matrix flaten
np.tile(np.arange(x.shape[0]),2*wz+1) #repeating `x` indexes to each window position
))
x[ri[:,(ri[0]>=0)&(ri[0]<x.shape[0])]]#.T #uncomment .T to make it vertical
Output:
[[1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 2, 3, 4],
[3, 4, 1, 3, 4, 1, 2, 3, 4, 1, 2, 4, 1, 2]]
Update 1 (error fix)
exclude zero from window to avoid pair duplication.
x = np.array([1,2,3,4])
wz = 2
ri = np.vstack(((
np.hstack(( np.arange(-wz,0), #remove zero from window
np.arange(1,wz+1)))+
np.arange(x.shape[0]).reshape(-1,1)).ravel(), #same index matrix flaten
np.tile(np.arange(x.shape[0]),2*wz) #repeating `x` indexes to each window position
))
x[ri[:,(ri[0]>=0)&(ri[0]<x.shape[0])]]#.T #uncomment .T to make it vertical
Output:
[[2, 3, 1, 3, 4, 1, 2, 4, 2, 3],
[3, 4, 2, 3, 4, 1, 2, 3, 1, 2]]
Check documentation on used functions np.arange, np.reshape, np.place, np.hstack, broadcasting rules and indexing.