python 2.6.6 と numpy バージョン 1.5.0 を使用して、2D numpy 配列にゼロを埋め込む方法を知りたいです。しかし、これらは私の限界です。したがって、私は使用できませんnp.pad
。たとえばa
、形状が一致するようにゼロをパディングしたいとしb
ます。私がこれをやりたい理由は、私ができるようにするためです:
b-a
そのような
>>> 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]])
これを行う唯一の方法は追加ですが、これはかなり醜いようです。おそらく使用するよりクリーンなソリューションはありb.shape
ますか?
編集、MSeifertsの回答に感謝します。私はそれを少しきれいにしなければなりませんでした、そしてこれは私が得たものです:
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