索引numpy多维数组取决于切片方法 [英] Indexing numpy multidimensional arrays depends on a slicing method
问题描述
我有一个3-D阵列.当我对它进行二维切片时,结果取决于它是用列表索引还是用切片索引.在第一种情况下,结果被转置.在手册中未找到此行为.. >
I have a 3-D array. When I take a 2-D slice of it the result depends on whether it is indexed with a list or with a slice. In the first case the result is transposed. Didn't find this behaviour in the manual.
>>> import numpy as np
>>> x = np.array([[[1,1,1],[2,2,2]], [[3,3,3],[4,4,4]]])
>>> x
array([[[1, 1, 1],
[2, 2, 2]],
[[3, 3, 3],
[4, 4, 4]]])
>>> x[0,:,[0,1]]
array([[1, 2],
[1, 2]])
>>> x[0,:,slice(2)]
array([[1, 1],
[2, 2]])
>>>
有人可以为此指出理由吗?
Could anyone point a rationale for this?
推荐答案
据我了解,当给定类似list/tuple
的索引时,NumPy吐出结果时会遵循轴编号原理.
As I understand it, NumPy is following the axis numbering philosophy when it spits out the result when given a list/tuple
-like index.
array([[[1, 1, 1],
[2, 2, 2]],
[[3, 3, 3],
[4, 4, 4]]])
当您已经指定了前两个索引(x[0, :, ]
)时,接下来的问题是如何提取第三维.现在,当您指定一个元组(0,1)
时,它首先会明智地提取0
个切片轴,因此它会得到[1, 2]
,因为它位于第0
个轴上,接下来它将同样提取1
st个切片并堆叠在已存在的行[1, 2]
下.
When you already specify the first two indices (x[0, :, ]
), now the next question is how to extract the third dimension. Now, when you specify a tuple (0,1)
, it first extracts the 0
th slice axis wise, so it gets [1, 2]
since it lies in 0
th axis, next it extracts 1
st slice likewise and stacks below the already existing row [1, 2]
.
[[1, 1, 1], array([[1, 2],
[2, 2, 2]] =====> [1, 2]])
(由于第0轴向下生长,因此已可视化堆栈(如下所示(不在上方))
(visualize this stacking as below (not on top of) the already existing row since axis-0 grows downwards)
或者,当为索引指定slice(n)
时,它遵循切片原理(start
:stop
:step
).请注意,在您的示例中,使用slice(2)
本质上等于0:2
.因此,它首先提取[1, 1]
,然后提取[2, 2]
.请注意,这里[1, 1]
是如何出现在[2, 2]
之上的,再次遵循这里相同的轴原理,因为我们还没有离开三维.这就是为什么这个结果是另一个的转置的原因.
Alternatively, it is following the slicing philosophy (start
:stop
:step
) when slice(n)
is given for the index. Note that using slice(2)
is essentially equal to 0:2
in your example. So, it extracts [1, 1]
first, then [2, 2]
. Note, here to how [1, 1]
comes on top of [2, 2]
, again following the same axis philosophy here since we didn't leave the third dimension yet. This is why this result is the transpose of the other.
array([[1, 1],
[2, 2]])
此外,请注意,从3-D数组开始,将保持这种一致性.下面是4-D
数组和切片结果的示例.
Also, note that starting from 3-D arrays this consistency is preserved. Below is an example from 4-D
array and the slicing results.
In [327]: xa
Out[327]:
array([[[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]],
[[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]],
[[27, 28, 29],
[30, 31, 32],
[33, 34, 35]]]])
In [328]: xa[0, 0, :, [0, 1]]
Out[328]:
array([[0, 3, 6],
[1, 4, 7]])
In [329]: xa[0, 0, :, 0:2]
Out[329]:
array([[0, 1],
[3, 4],
[6, 7]])
这篇关于索引numpy多维数组取决于切片方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!