numpyのバージョン1.5.0でPython 2.6.6を使用して2次元numpy配列に0を埋め込む方法を知りたいと思います。ごめんなさい!しかし、これは私の限界です。したがって、np.pad
は使用できません。例えば、a
に0を付けて、その形がb
に一致するようにしたいとします。私はこれをしたい理由は、私にできるそうですが、これはかなり醜いようだpython numpy配列に0を埋め込む方法
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
パディングなしでやる方法を提案できますか? – purpletentacle