Ich möchte wissen, wie ich ein 2D-numpy-Array mit Nullen mit Python 2.6.6 mit numpy Version 1.5.0 auffüllen kann. Es tut uns leid! Aber das sind meine Grenzen. Daher kann ich np.pad
nicht verwenden. Zum Beispiel möchte ich a
mit Nullen auffüllen, so dass seine Form b
entspricht. Der Grund, warum ich dies tun wollen ist, so kann ich tun:Python, wie man numpy Array mit Nullen pad
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]])
Die einzige Art, wie ich dies zu tun, ist das Anhängen denken kann, aber das ist ziemlich hässlich zu sein scheint. Gibt es eine sauberere Lösung, die möglicherweise b.shape
verwendet?
Bearbeiten, Vielen Dank an MSeiferts Antwort. Ich musste es sauber ein wenig, und das ist, was ich habe:
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
Kann ich Ihnen einen Weg vorschlagen, dies ohne Polsterung zu tun? – purpletentacle