python怎么填充数组_python如何用零填充numpy数组

I want to know how I can pad a 2D numpy array with zeros using python 2.6.6 with numpy version 1.5.0. Sorry! But these are my limitations. Therefore I cannot use np.pad. For example, I want to pad a with zeros such that its shape matches b. The reason why I want to do this is so I can do:

b-a

such that

>>> 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]])

The only way I can think of doing this is appending, however this seems pretty ugly. is there a cleaner solution possibly using b.shape?

Edit,

Thank you to MSeiferts answer. I had to clean it up a bit, and this is what I got:

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

解决方案

Very simple, you create an array containing zeros using the reference shape:

result = np.zeros(b.shape)

# actually you can also use result = np.zeros_like(b)

# but that also copies the dtype not only the shape

and then insert the array where you need it:

result[:a.shape[0],:a.shape[1]] = a

and voila you have padded it:

print(result)

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.]])

You can also make it a bit more general if you define where your upper left element should be inserted

result = np.zeros_like(b)

x_offset = 1 # 0 would be what you wanted

y_offset = 1 # 0 in your case

result[x_offset:a.shape[0]+x_offset,y_offset:a.shape[1]+y_offset] = a

result

array([[ 0., 0., 0., 0., 0., 0.],

[ 0., 1., 1., 1., 1., 1.],

[ 0., 1., 1., 1., 1., 1.],

[ 0., 1., 1., 1., 1., 1.]])

but then be careful that you don't have offsets bigger than allowed. For x_offset = 2 for example this will fail.

If you have an arbitary number of dimensions you can define a list of slices to insert the original array. I've found it interesting to play around a bit and created a padding function that can pad (with offset) an arbitary shaped array as long as the array and reference have the same number of dimensions and the offsets are not too big.

def pad(array, reference, offsets):

"""

array: Array to be padded

reference: Reference array with the desired shape

offsets: list of offsets (number of elements must be equal to the dimension of the array)

"""

# 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(offset[dim], offset[dim] + array.shape[dim]) for dim in range(a.ndim)]

# Insert the array in the result at the specified offsets

result[insertHere] = a

return result

And some test cases:

import numpy as np

# 1 Dimension

a = np.ones(2)

b = np.ones(5)

offset = [3]

pad(a, b, offset)

# 3 Dimensions

a = np.ones((3,3,3))

b = np.ones((5,4,3))

offset = [1,0,0]

pad(a, b, offset)

numpy数组元素周围的操作可以通过以下几种方式实现: 1. 切片操作:可以使用numpy数组的切片操作来获取数组中元素的周围元素。 例如,对于一个二维数组arr,要获取第i行第j列元素周围的元素,可以使用如下切片操作: ```python arr[i-1:i+2, j-1:j+2] ``` 这将返回一个3x3的子数组,其中心元素为arr[i,j],周围的8个元素为该子数组的其余元素。 2. 使用numpy.pad()函数:numpy.pad()函数可以用来在数组的边缘添加一个或多个值,从而扩展数组的大小。可以使用该函数来添加额外的行和列,然后通过索引访问周围的元素。 例如,对于一个二维数组arr,要获取第i行第j列元素周围的元素,可以使用如下代码: ```python padded_arr = np.pad(arr, ((1, 1), (1, 1)), mode='constant') surrounding = padded_arr[i:i+3, j:j+3] ``` 这将在数组的边缘添加一行和一列,并使用常量值填充这些额外的元素。然后可以使用切片操作来获取中心元素周围的元素。 3. 使用numpy.roll()函数:numpy.roll()函数可以用来沿着给定轴滚动数组的元素。可以使用该函数来将数组的行和列进行滚动,从而获取周围的元素。 例如,对于一个二维数组arr,要获取第i行第j列元素周围的元素,可以使用如下代码: ```python rows, cols = arr.shape row_indices = np.arange(i-1, i+2) % rows col_indices = np.arange(j-1, j+2) % cols surrounding = arr[row_indices][:, col_indices] ``` 这将将第i行向上和向下滚动一行,并将第j列向左和向右滚动一列,从而获取中心元素周围的元素。使用模运算可以确保在数组的边缘滚动时正确处理索引。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值