Arrays 多维切片

Arrays 多维切片,arrays,python-2.7,performance,numpy,slice,Arrays,Python 2.7,Performance,Numpy,Slice,我想多次切掉数组foo中的部分。目前我正在使用一个for循环,我想通过矩阵计算来替代它,以获得更好的速度性能 foo = np.arange(6000).reshape(6,10,10,10) target = np.zeros((100,6,3,4,5)) startIndices = np.random.randint(5, size=(100)) 这是我目前的做法 for i in range(len(target)): startIdx=startIndices[i]

我想多次切掉数组
foo
中的部分。目前我正在使用一个for循环,我想通过矩阵计算来替代它,以获得更好的速度性能

foo = np.arange(6000).reshape(6,10,10,10)
target = np.zeros((100,6,3,4,5))
startIndices = np.random.randint(5, size=(100))
这是我目前的做法

for i in range(len(target)):
    startIdx=startIndices[i]
    target[i, :]=foo[:, startIdx:startIdx+3,
                        startIdx:startIdx+4,
                        startIdx:startIdx+5]
我试图将切片表示为数组,但找不到正确的表示形式

我们可以利用based进行高效的补丁提取,就像这样-

from skimage.util.shape import view_as_windows

# Get sliding windows (these are simply views)
WSZ = (1,3,4,5) # window sizes along the axes
w = view_as_windows(foo,WSZ)[...,0,:,:,:]

# Index with startIndices along the appropriate axes for desired output
out = w[:,startIndices, startIndices, startIndices].swapaxes(0,1)
相关的: