numpy.pad
with constant
模式可以满足您的需要,我们可以传递一个元组作为第二个参数来告诉每个大小要填充多少个零,(2, 3)
例如将垫2左侧的零和3右边的零:
Given A
as:
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])
还可以通过传递元组的元组作为填充宽度来填充 2D 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]])
对于您的情况,您指定左侧为零,右侧垫根据模除法计算:
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