我想知道如何用numpy 1.5.0版使用python 2.6.6填充二維numpy數組。抱歉!但這些是我的限制。所以我不能使用np.pad
。例如,我想用零填充a
,使其形狀匹配b
。爲什麼我想這樣做的原因是,所以我可以做的:python如何用零填充numpy數組
b-a
這樣
>>> a
array([[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.],
[ 1., 1., 1., 1., 1.]])
>>> b
array([[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.],
[ 3., 3., 3., 3., 3., 3.]])
>>> c
array([[1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0]])
我認爲這樣做是追加的唯一途徑,然而,這似乎是相當難看。有沒有更清潔的解決方案可能使用b.shape
?
編輯, 謝謝MSeiferts的回答。我不得不把它清理乾淨了一下,這是我得到了什麼:
def pad(array, reference_shape, offsets):
"""
array: Array to be padded
reference_shape: tuple of size of ndarray to create
offsets: list of offsets (number of elements must be equal to the dimension of the array)
will throw a ValueError if offsets is too big and the reference_shape cannot handle the offsets
"""
# Create an array of zeros with the reference shape
result = np.zeros(reference_shape)
# Create a list of slices from offset to offset + shape in each dimension
insertHere = [slice(offsets[dim], offsets[dim] + array.shape[dim]) for dim in range(array.ndim)]
# Insert the array in the result at the specified offsets
result[insertHere] = array
return result
我可以建議你一個辦法做到這一點沒有填充? – purpletentacle