Home > Mobile >  Create variable padding around 1d numpy array
Create variable padding around 1d numpy array

Time:09-17

arr= [1,2,3,4]
k = 4 (can be different)

so result will be 2 d array. How to do this without using any loop? and can't hard code k. k and arr can vary as per input. Must use numpy.pad

[[1,2,3,4,0,0,0], #k-1 zeros
 [0,1,2,3,4,0,0],
 [0,0,1,2,3,4,0],
 [0,0,0,1,2,3,4]]


CodePudding user response:

If you really have to do it without a loop (for educational purposes)

np.pad(np.tile(arr,[k,1]), [(0,0),(0,k)]).reshape(-1)[:-k].reshape(k,-1)

CodePudding user response:

Using list comprehension as a one liner :

import numpy as np

arr= np.array([1,2,3,4])
k = 4

print( np.array( [ np.pad(arr, (0 i , k-1-i ) ) for i in range(0,k)] ) )

Out :

[[1 2 3 4 0 0 0]
 [0 1 2 3 4 0 0]
 [0 0 1 2 3 4 0]
 [0 0 0 1 2 3 4]]
  • Related