Florian Florian - 4 months ago 7
Python Question

Adding the previous n rows as columns to a numpy array

I want to add the previous n rows as columns to a numpy array. Here is an example:

For n=2 this:
[[ 1, 2]
[ 3, 4]
[ 5, 6]
[ 7, 8]
[ 9, 10]
[11, 12]]

Should be turned into this:
[[ 1, 2, 0, 0, 0, 0]
[ 3, 4, 1, 2, 0, 0]
[ 5, 6, 3, 4, 1, 2]
[ 7, 8, 5, 6, 3, 4]
[ 9, 10, 7, 8, 5, 6]
[11, 12, 9, 10, 7, 8]]


Any ideas how I could do that without going over the entire array in a loop.

Answer

Here is a way to pad 0 in the beginning of the array and then column stack them:

import numpy as np
n = 2
def mypad(myArr, n):
    if n == 0:
        return myArr
    else:
        return np.pad(myArr, ((n,0), (0,0)), mode = "constant")[:-n]

np.column_stack(mypad(arr, i) for i in range(n + 1))

# array([[ 1,  2,  0,  0,  0,  0],
#        [ 3,  4,  1,  2,  0,  0],
#        [ 5,  6,  3,  4,  1,  2],
#        [ 7,  8,  5,  6,  3,  4],
#        [ 9, 10,  7,  8,  5,  6],
#        [11, 12,  9, 10,  7,  8]])