0

I have numpy array as follows:

train_x = [[1,2,3,0,0], [2,5,0,0,0], [2,3,0,0,0], [0,0,0,0,0], [0,0,0,0,0,0]]

Now, I would like to transform it to as shown below:

new_train_x = [[0,0,0,0,0],[0,0,0,0,0,0],[0,0,1,2,3],[0,0,0,2,5],[0,0,0,2,3]]

I tried writing manually. The length of such list is huge. But it is time consuming.

I would like to know the efficient and short code for this (manually takes time).

Ethan
  • 1,633
  • 9
  • 24
  • 39
Abc1729
  • 15
  • 4
  • it is not possible if you dont konw the amount of padding of each input or if padding is fixed and consistent – Nikos M. Aug 13 '21 at 18:00

1 Answers1

0

So assuming that the padding is the same length and the shape of the array is consistent you can do something below:

        import numpy as np
        train_x = np.array([[1,2,3,0,0], [2,5,0,0,0], [2,3,0,0,0], [0,0,0,0,0], [0,0,0,0,0,0]])
        stringX = ''
        for i in train_x:
            for s in i:
                stringX += str(s)
            subStrX = stringX[0:12]
        prePadStr ='00000000000000' + subStrX
    counter = 0
    internalCounter = 0
    newStr = ''
    newLst = np.empty(shape=([5,5]),dtype=str)
    while counter < 25: 
        newStr = prePadStr[counter:counter+5]
        newStrLst = [char for char in newStr]
        newLst[internalCounter] = newStrLst
        counter+=5
        internalCounter+=1
    newLst

If you need something that should be able to infer the padding and shape, I can provide that as well. However when it comes to efficiency, that will likely isn't the case that this is the most efficient, but that may not matter depending on what you have to process.