1

I have an array like [1,3,4,5,6,2,1,,,,]

now, I want to change it to [[1,3,4],[3,4,5],[4,5,6],[5,6,2],,,,]

How can I achieve this using numpy? Is there any function to do so? And, using loop is not an option.

Ébe Isaac
  • 11,563
  • 17
  • 64
  • 97
Junnan Wang
  • 627
  • 4
  • 12
  • Is that really an array, or just a list? And how big? What are you going to do with the result? There is an array method using `stride_tricks`, but that's for 'advanced users'. – hpaulj Nov 15 '16 at 05:40

2 Answers2

2

np.lib.stride_tricks.as_strided method will does that.

Here strides is (4,4) for 32 bit int. If you want more flexible code, I have commented stride parameter in the code. shape parameter determines output array dimensions.

> import numpy as np
> A = [1,2,3,4,5,6]
> n = 3 # output matrix has 3 columns
> m = len(A) - (n-1) # calculate number of output matrix rows using input matrix length
> # strides_param = np.array(A, dtype=np.int32).strides * 2
> np.lib.stride_tricks.as_strided(A, shape=(m,n), strides=(4,4))
array([[1, 2, 3],
       [2, 3, 4],
       [3, 4, 5],
       [4, 5, 6]])
TRiNE
  • 5,020
  • 1
  • 29
  • 42
1

Using list comprehension instead of a library but why make it complicated. (Do you consider this a loop?)

x = [1,3,4,5,6,2,1]
y = [x[n:n+3] for n in range(len(x)-2)]

Result is:

[[1, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 2], [6, 2, 1]]
beroe
  • 11,784
  • 5
  • 34
  • 79