我有一个 3d 数组,我想获得一个以索引 indx 为中心的大小为 (2n+1) 的子数组。使用我可以使用的切片
y[slice(indx[0]-n,indx[0]+n+1),slice(indx[1]-n,indx[1]+n+1),slice(indx[2]-n,indx[2]+n+1)]
如果我想为每个维度设置不同的尺寸,那只会变得更丑。有没有更好的方法来做到这一点。
slice
除非您想存储切片对象以供以后使用,否则您不需要使用构造函数。相反,您可以简单地执行以下操作:
y[indx[0]-n:indx[0]+n+1, indx[1]-n:indx[1]+n+1, indx[2]-n:indx[2]+n+1]
如果您想在不单独指定每个索引的情况下执行此操作,则可以使用列表推导:
y[[slice(i-n, i+n+1) for i in indx]]
您可以创建 numpy 数组以索引到不同维度的3D array
,然后使用 useix_
函数创建索引映射,从而获得切片输出。这样做的好处ix_
是它允许广播索引地图。更多信息可以在这里找到。然后,您可以为通用解决方案的每个维度指定不同的窗口大小。这是带有示例输入数据的实现 -
import numpy as np
A = np.random.randint(0,9,(17,18,16)) # Input array
indx = np.array([5,10,8]) # Pivot indices for each dim
N = [4,3,2] # Window sizes
# Arrays of start & stop indices
start = indx - N
stop = indx + N + 1
# Create indexing arrays for each dimension
xc = np.arange(start[0],stop[0])
yc = np.arange(start[1],stop[1])
zc = np.arange(start[2],stop[2])
# Create mesh from multiple arrays for use as indexing map
# and thus get desired sliced output
Aout = A[np.ix_(xc,yc,zc)]
因此,对于具有窗口大小数组的给定数据,N = [4,3,2]
信息whos
显示 -
In [318]: whos
Variable Type Data/Info
-------------------------------
A ndarray 17x18x16: 4896 elems, type `int32`, 19584 bytes
Aout ndarray 9x7x5: 315 elems, type `int32`, 1260 bytes
输出的whos
信息Aout
似乎与预期的输出形状一致,必须是2N+1
.