numpy.pad 和 constant 模式可以满足您的需求,我们可以传递一个元组作为第二个参数来告诉每个尺寸要填充多少个零,例如 (2, 3) 将填充 2 左侧为零,右侧 3 个零:
给定A:
A = np.array([1,2,3,4,5])
np.pad(A, (2, 3), 'constant')
# array([0, 0, 1, 2, 3, 4, 5, 0, 0, 0])
还可以通过传递元组的元组作为填充宽度来填充二维 numpy 数组,其格式为 ((top, bottom), (left, right)):
A = np.array([[1,2],[3,4]])
np.pad(A, ((1,2),(2,1)), 'constant')
#array([[0, 0, 0, 0, 0], # 1 zero padded to the top
# [0, 0, 1, 2, 0], # 2 zeros padded to the bottom
# [0, 0, 3, 4, 0], # 2 zeros padded to the left
# [0, 0, 0, 0, 0], # 1 zero padded to the right
# [0, 0, 0, 0, 0]])
对于您的情况,您指定左侧为零,右侧 pad 由模除法计算得出:
B = np.pad(A, (0, 1024 - len(A)%1024), 'constant')
B
# array([1, 2, 3, ..., 0, 0, 0])
len(B)
# 1024
对于更大的A:
A = np.ones(3000)
B = np.pad(A, (0, 1024 - len(A)%1024), 'constant')
B
# array([ 1., 1., 1., ..., 0., 0., 0.])
len(B)
# 3072