我想知道如何使用带有 numpy 版本 1.5.0 的 python 2.6.6 用零填充 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
原文由 user2015487 发布,翻译遵循 CC BY-SA 4.0 许可协议
非常简单,您可以使用参考形状创建一个包含零的数组:
然后在需要的地方插入数组:
瞧,您已经填充了它:
如果您定义左上角元素应插入的位置,也可以使其更通用
但是请注意,您的偏移量不要超过允许的值。对于
x_offset = 2
例如,这将失败。如果您有任意数量的维度,您可以定义一个切片列表来插入原始数组。我发现玩一点很有趣,并创建了一个填充函数,只要数组和引用具有相同的维数并且偏移量不是太大,它就可以填充(带有偏移量)任意形状的数组。
还有一些测试用例: