Chcę wiedzieć, jak mogę uzupełnić tablicę numpy 2D zerami za pomocą Pythona 2.6.6 z Numpy w wersji 1.5.0. Przepraszam! Ale to są moje ograniczenia. Dlatego nie mogę użyć np.pad. Na przykład chcę dopełnić azerami tak, aby pasował do kształtu b. Powód, dla którego chcę to zrobić, jest taki, że mogę:
b-a
takie że
>>> 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]])
Jedyny sposób, w jaki mogę o tym pomyśleć, to dołączanie, jednak wydaje się to dość brzydkie. czy jest możliwe użycie czystszego rozwiązania b.shape?
Edytuj, dziękuję za odpowiedź MSeiferts. Musiałem to trochę posprzątać i oto co dostałem:
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