本文介绍了沿动态指定的轴切片一个 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想沿特定轴动态切片一个 numpy 数组.鉴于此:
轴 = 2开始 = 5结束 = 10
我想达到与此相同的结果:
# m 是一些矩阵m[:,:,5:10]
使用这样的东西:
slc = tuple(:,) * len(m.shape)slc[轴] = 切片(开始,结束)米[slc]
但是 :
值不能放在元组中,所以我不知道如何构建切片.
解决方案
我认为一种方法是使用 slice(None)
:
我有一种模糊的感觉,我以前为此使用过一个函数,但现在似乎找不到了..
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]
Using something like this:
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.
解决方案
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 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!