[英]Numpy multidimensional array slicing
Suppose I have defined a 3x3x3 numpy array with 假设我已经定义了一个3x3x3 numpy数组
x = numpy.arange(27).reshape((3, 3, 3))
Now, I can get an array containing the (0,1) element of each 3x3 subarray with x[:, 0, 1]
, which returns array([ 1, 10, 19])
. 现在,我可以得到一个包含每个3x3子阵列的(0,1)元素的数组,其中包含
x[:, 0, 1]
,它返回array([ 1, 10, 19])
。 What if I have a tuple (m,n) and want to retrieve the (m,n) element of each subarray(0,1) stored in a tuple? 如果我有一个元组(m,n)并想要检索存储在元组中的每个子数组(0,1)的(m,n)元素,该怎么办?
For example, suppose that I have t = (0, 1)
. 例如,假设我有
t = (0, 1)
。 I tried x[:, t]
, but it doesn't have the right behaviour - it returns rows 0 and 1 of each subarray. 我尝试了
x[:, t]
,但它没有正确的行为 - 它返回每个子数组的行0和1。 The simplest solution I have found is 我发现最简单的解决方案是
x.transpose()[tuple(reversed(t))].transpose()
but I am sure there must be a better way. 但我相信一定有更好的方法。 Of course, in this case, I could do
x[:, t[0], t[1]]
, but that can't be generalised to the case where I don't know how many dimensions x
and t
have. 当然,在这种情况下,我可以做
x[:, t[0], t[1]]
,但这不能推广到我不知道x
和t
有多少维度的情况。
你可以先创建索引元组:
index = (numpy.s_[:],)+t
x[index]
HYRY solution is correct, but I have always found numpy's r_
, c_
and s_
index tricks to be a bit strange looking. HYRY解决方案是正确的,但我总是发现numpy的
r_
, c_
和s_
索引技巧看起来有点奇怪。 So here is the equivalent thing using a slice
object: 所以这是使用
slice
对象的等价物:
x[(slice(None),) + t]
That single argument to slice is the stop position (ie None
meaning all in the same way that x[:]
is equivalent to x[None:None]
) 切片的单个参数是停止位置(即
None
表示所有与x[:]
等效于x[None:None]
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.