沿动态指定的轴切片numpy数组 [英] Slicing a numpy array along a dynamically specified axis
本文介绍了沿动态指定的轴切片numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想沿特定轴动态切片一个numpy数组.鉴于此:
I would like to dynamically slice a numpy array along a specific axis. Given this:
axis = 2
start = 5
end = 10
我想要达到相同的结果:
I want to achieve the same result as this:
# m is some matrix
m[:,:,5:10]
使用类似这样的内容:
slc = tuple(:,) * len(m.shape)
slc[axis] = slice(start,end)
m[slc]
但是:
值不能放在元组中,所以我不知道如何构建切片.
But the :
values can't be put in a tuple, so I can't figure out how to build the slice.
推荐答案
我认为一种方法是使用slice(None)
:
I think one way would be to use 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
我有一种模糊的感觉,我以前曾经为此使用过一个函数,但是现在似乎找不到了.
I have a vague feeling I've used a function for this before, but I can't seem to find it now..
这篇关于沿动态指定的轴切片numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文