沿动态指定轴切片numpy数组

2024-05-16 03:38:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我想沿着一个特定的轴动态切片一个numpy数组。鉴于此:

axis = 2
start = 5
end = 10

我想达到同样的效果:

# m is some matrix
m[:,:,5:10]

使用这样的东西:

slc = tuple(:,) * len(m.shape)
slc[axis] = slice(start,end)
m[slc]

但是:值不能放在元组中,所以我不知道如何构建切片。


Tags: numpylenis动态切片some数组start
3条回答

因为它没有被清楚地提及(我也在寻找它):

相当于:

a = my_array[:, :, :, 8]
b = my_array[:, :, :, 2:7]

是:

a = my_array.take(indices=8, axis=3)
b = my_array.take(indices=range(2, 7), axis=3)

我认为一种方法是使用slice(None)

>>> m = np.arange(2*3*5).reshape((2,3,5))
>>> axis, start, end = 2, 1, 3
>>> target = m[:, :, 1:3]
>>> target
array([[[ 1,  2],
        [ 6,  7],
        [11, 12]],

       [[16, 17],
        [21, 22],
        [26, 27]]])
>>> slc = [slice(None)] * len(m.shape)
>>> slc[axis] = slice(start, end)
>>> np.allclose(m[slc], target)
True

我有一种模糊的感觉,我以前用过这个函数,但现在好像找不到了。。

这对派对来说有点晚了,但默认的Numpy方式是^{}。但是,这个总是复制数据(因为它支持奇特的索引,所以它总是假设这是可能的)。为了避免这种情况(在许多情况下,您需要的是数据的视图,而不是副本),请回退到另一个答案中已经提到的slice(None)选项,可能将其包装成一个很好的函数:

def simple_slice(arr, inds, axis):
    # this does the same as np.take() except only supports simple slicing, not
    # advanced indexing, and thus is much faster
    sl = [slice(None)] * arr.ndim
    sl[axis] = inds
    return arr[tuple(sl)]

相关问题 更多 >