python - Transform 2D array to a 3D array with overlapping strides -


i convert 2d array 3d previous rows using numpy or native functions.

input:

[[1,2,3],  [4,5,6],  [7,8,9],  [10,11,12],  [13,14,15]] 

output:

[[[7,8,9],    [4,5,6],    [1,2,3]],  [[10,11,12], [7,8,9],    [4,5,6]],  [[13,14,15], [10,11,12], [7,8,9]]] 

any 1 can help? have searched online while, cannot got answer.

approach #1

one approach np.lib.stride_tricks.as_strided gives view input 2d array , such doesn't occupy anymore of memory space -

l = 3  # window length sliding along first axis s0,s1 = a.strides  shp = a.shape out_shp = shp[0] - l + 1, l, shp[1] strided = np.lib.stride_tricks.as_strided out = strided(a[l-1:], shape=out_shp, strides=(s0,-s0,s1)) 

sample input, output -

in [43]: out[43]:  array([[ 1,  2,  3],        [ 4,  5,  6],        [ 7,  8,  9],        [10, 11, 12],        [13, 14, 15]])  in [44]: out out[44]:  array([[[ 7,  8,  9],         [ 4,  5,  6],         [ 1,  2,  3]],         [[10, 11, 12],         [ 7,  8,  9],         [ 4,  5,  6]],         [[13, 14, 15],         [10, 11, 12],         [ 7,  8,  9]]]) 

approach #2

alternatively, bit easier 1 broadcasting upon generating of row indices -

in [56]: a[range(l-1,-1,-1) + np.arange(shp[0]-l+1)[:,none]] out[56]:  array([[[ 7,  8,  9],         [ 4,  5,  6],         [ 1,  2,  3]],         [[10, 11, 12],         [ 7,  8,  9],         [ 4,  5,  6]],         [[13, 14, 15],         [10, 11, 12],         [ 7,  8,  9]]]) 

Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -