Home > Net >  Adding zeroes at the end of an array based on the length the a Numpy Array Python
Adding zeroes at the end of an array based on the length the a Numpy Array Python

Time:01-13

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]

CodePudding user response:

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

CodePudding user response:

val=[1,4,11]

def Adjust(limit):
    return val   [0] * (max(0, limit - len(val)))

def dbg(limit):
    print(Adjust(limit))

dbg(5)
dbg(2)
dbg(3)
dbg(6)
  • [0] * n creates an array of zeroes with len n
  • a1 a2 concatenates two arrays
  •  Tags:  
  • Related