1

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.

1
  • 1
    a = [1, 2, 3, 4; 5, 6, 7, 8] is invalid Python syntax. Commented Feb 26, 2019 at 17:13

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.