Home > Software engineering >  Tiling with offsets in Numpy
Tiling with offsets in Numpy

Time:03-28

Say I have the following np.array():

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

I would like to tile the values across with an offset. In this case we group by three and offset by 1:

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

Is there a built in function to achieve this that leverages C internals of numpy? I'm working with very long arrays and using standard array manipulation with loops has been prohibitively slow.

CodePudding user response:

Based on the explanation in the question, if the expected array be as (not that is written now without [5, 6, 7], [6, 7, 8]):

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

The easiest way is mentioned by @ Michael Szczesny.
But, based on one of SO answers and by modifying that to adapt with this question:

a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
slice_ = 2
b = np.tile(a, (len(a) - slice_, 1))
rolling_val = np.arange(len(b))   slice_   1
rows, column_indices = np.ogrid[:b.shape[0], :b.shape[1]]
column_indices = column_indices - rolling_val[:, np.newaxis]
result = b[rows, column_indices]
result = result[::-1][:len(a) - slice_, :slice_   1]

CodePudding user response:

You can use numpy.lib.stride_tricks.sliding_window_view like below:

numpy.lib.stride_tricks.sliding_window_view is New in version 1.20.0. you need update your numpy if you numpy didn't update.

arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
np.lib.stride_tricks.sliding_window_view(arr , 3)

Output:

array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6],
       [5, 6, 7],
       [6, 7, 8],
       [7, 8, 9]])
  • Related