python wie man numpy array mit Nullen auffüllt

Möchte ich wissen, wie kann ich das pad eine 2D-numpy-array mit Nullen mit python 2.6.6 mit numpy version 1.5.0. Sorry! Aber diese sind meine Grenzen. Daher kann ich nicht verwenden np.pad. Zum Beispiel, ich möchte pad a mit Nullen, so dass seine Form entspricht b. Der Grund, warum ich dies tun wollen ist, so kann ich tun:

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]])

Nur so kann ich mir vorstellen, dies zu tun, ist das Anhängen, aber es scheint ziemlich hässlich. gibt es eine sauberere Lösung evtl. mit b.shape?

Bearbeiten,
Vielen Dank an MSeiferts Antwort. Ich hatte zu reinigen es 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

InformationsquelleAutor der Frage user2015487 | 2016-03-02

Schreibe einen Kommentar