Zero pad numpy array

后端 未结 5 1729
时光说笑
时光说笑 2020-12-02 18:06

What\'s the more pythonic way to pad an array with zeros at the end?

def pad(A, length):
    ...

A = np.array([1,2,3,4,5])
pad(A, 8)    # expected : [1,2,3,         


        
5条回答
  •  有刺的猬
    2020-12-02 19:07

    You could also use numpy.pad:

    >>> A = np.array([1,2,3,4,5])
    >>> npad = 8 - len(A)
    >>> np.pad(A, pad_width=npad, mode='constant', constant_values=0)[npad:]
    array([1, 2, 3, 4, 5, 0, 0, 0])
    

    And in a function:

    def pad(A, npads):
        _npads = npads - len(A)
        return np.pad(A, pad_width=_npads, mode='constant', constant_values=0)[_npads:]
    

提交回复
热议问题