Eu quero saber como posso preencher um array numpy 2D com zeros usando python 2.6.6 com numpy versão 1.5.0. Desculpa! Mas essas são minhas limitações. Portanto, não posso usar np.pad. Por exemplo, desejo preencher acom zeros de forma que sua forma corresponda b. O motivo pelo qual quero fazer isso é:
b-a
de tal modo que
>>> 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]])
A única maneira que consigo pensar em fazer isso é anexando, no entanto, parece muito feio. existe uma solução mais limpa possivelmente usando b.shape?
Editar, obrigado à resposta de MSeiferts. Tive que limpar um pouco e foi isso que consegui:
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