Newbie0105
Newbie0105

Reputation: 119

Slice array, but overlapped interval in Python

There are 3D-array in my data. I just want to slice 3D-array 2 by 2 by 2 with overlapped interval in Python.

Here is an example for 2D.

a = [1, 2, 3, 4;
     5, 6, 7, 8]

Also, this is what I expected after slicing the array in 2 by 2.

[1, 2;  [2, 3;  [3, 4;
 5, 6]   6, 7]   7, 8]

In 3D,

  [[[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]],

   [[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]],

   [[1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]]]

Like this,(maybe not exactly..)

 [1, 2   [2, 3
  4, 5]   5, 6]       ...
 [1, 2   [2, 3
  4, 5]   5, 6] 

I think, by using np.split, I could slice the array, but without overlapped. Please give me some helpful tips.

Upvotes: 1

Views: 625

Answers (1)

mrk
mrk

Reputation: 10406

You should have a look at numpy.ndarray.strides and numpy.lib.stride_tricks

Tuple of bytes to step in each dimension when traversing an array. The byte offset of element (i[0], i[1], ..., i[n]) in an array a is:

offset = sum(np.array(i) * a.strides)

See also the numpy documentation

Following a 2D example using strides:

x = np.arange(20).reshape([4, 5])
>>> x
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])

>>> from numpy.lib import stride_tricks
>>> stride_tricks.as_strided(x, shape=(3, 2, 5),
                                strides=(20, 20, 4))
...
array([[[  0,  1,  2,  3,  4],
        [  5,  6,  7,  8,  9]],

       [[  5,  6,  7,  8,  9],
        [ 10, 11, 12, 13, 14]],

       [[ 10, 11, 12, 13, 14],
        [ 15, 16, 17, 18, 19]]])

Also see this question on Stackoverflow, where this example is from, to increase your understanding.

Upvotes: 1

Related Questions