Ad

Adding Zeroes At The End Of An Array Based On The Length The A Numpy Array Python

- 1 answer

How would I be able to make a function that adds zeroes at the ending of the numpy array if they are below the limit. So the val array below will be transformed into the Expected Outputs below.

Code:

import numpy as np

val=np.array([1,4,11])

def Adjust(limit):
    #Funtion needed


Adjust(5)
Adjust(2)
Adjust(3)
Adjust(6)

Expected Output:

[1,4,11,0,0]
[1,4,11]
[1,4,11]
[1,4,11,0,0,0]
Ad

Answer

def Adjust(arr, limit):
    if len(arr)<limit:
        return np.concatenate([arr, np.zeros(limit-len(arr), dtype = arr.dtype)])
    return arr
Ad
source: stackoverflow.com
Ad