2

Lets say I have the following array:

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

I want to generate an array that looks like this:

R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ..., [11,12,13,14]]

How can this be done with NumPy?

1 Answers1

4

How about this?

from numpy.lib import stride_tricks
Z = np.arange(1,15,dtype=np.uint32)
R = stride_tricks.as_strided(Z,(11,4),(4,4))
print(R)

Output:

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

As navneethc righly pointed out this function should be used with caution.

Geom
  • 1,491
  • 1
  • 10
  • 23
  • 2
    The documentation for this function has an important note on its behaviour, so it's advisable to read it before using it. https://numpy.org/doc/stable/reference/generated/numpy.lib.stride_tricks.as_strided.html – navneethc Aug 16 '20 at 12:20