0
$\begingroup$

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).

$\endgroup$
1
  • $\begingroup$ it is not possible if you dont konw the amount of padding of each input or if padding is fixed and consistent $\endgroup$
    – Nikos M.
    Aug 13 at 18:00
0
$\begingroup$

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.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.