Home > Net >  Slice numpy array with start position and offset back in the array
Slice numpy array with start position and offset back in the array

Time:08-09

I would like to slice a numpy array with a constant offset back in the array. I.e. start in the k'th position and go back n elements. I want to move the slight one index ahead at every iteration.

E.g. I have the following array

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

and let's say k is 5 and n is 3. That would give me the following (with ordering preserved)

x_sliced = [4, 5, 6]

In the next iteration k = 1 and n is still 3. That gives me the following array

x_sliced = [5, 6, 7]

I can sort of get the result but I'll have to flip the array to get back to the original order. Isn't there a clever way that just uses a position and an offset back in the array?

CodePudding user response:

If I understand correctly, this could help:

from skimage.util.shape import view_as_windows
k = 5
n = 3
view_as_windows(x[k-n 1:], n)

output:

array([[ 4,  5,  6],
       [ 5,  6,  7],
       [ 6,  7,  8],
       [ 7,  8,  9],
       [ 8,  9, 10]])

Then you can loop over the output rows and process each window. One thing to note is that the overlapping windows share the same memory. If you wish that changing the values in one window does not affect the next overlapping window, simply copy it (.copy())

CodePudding user response:

You can use np.lib.stride_tricks.as_strided for that which requires no other dependencies than NumPy itself!

x = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
b = np.lib.stride_tricks.as_strided(x, (len(x)-3 1, 3), 2 * x.strides)

b
> array([[ 1,  2,  3],
         [ 2,  3,  4],
         [ 3,  4,  5],
         [ 4,  5,  6],
         [ 5,  6,  7],
         [ 6,  7,  8],
         [ 7,  8,  9],
         [ 8,  9, 10]])

Moreover, with list(b) you can turn the 2D array into a list of 1D arrays.

  • Related