Ich möchte wissen, wie ich mit Python 2.6.6 mit Numpy Version 1.5.0 ein 2D-Numpy-Array mit Nullen auffüllen kann. Es tut uns leid! Aber das sind meine Grenzen. Daher kann ich nicht verwenden np.pad. Zum Beispiel möchte ich amit Nullen auffüllen, damit die Form übereinstimmt b. Der Grund, warum ich das tun möchte, ist, dass ich Folgendes tun kann:
b-a
so dass
>>> 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]])
Der einzige Weg, den ich mir vorstellen kann, ist das Anhängen, aber das scheint ziemlich hässlich. Gibt es möglicherweise eine sauberere Lösung b.shape?
Bearbeiten, danke an MSeiferts Antwort. Ich musste es ein bisschen aufräumen, und das habe ich bekommen:
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
padded = np.zeros(b.shape)padded[tuple(slice(0,n) for n in a.shape)] = a