[英]Using NumPy arrays as indices to NumPy arrays
I have a 3x3x3 NumPy array: 我有一个3x3x3 NumPy数组:
>>> x = np.arange(27).reshape((3, 3, 3))
>>> x
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]]])
Now I create an ordinary list of indices: 现在,我创建一个普通的索引列表:
>>> i = [[0, 1, 2, 1], [2, 1, 0, 1], [1, 2, 0, 1]]
As expected, I get four values using this list as the index: 不出所料,我使用此列表作为索引得到了四个值:
>>> x[i]
array([ 7, 14, 18, 13])
But if I now convert i
into a NumPy array, I won't get the same answer. 但是,如果现在将i
转换为NumPy数组,则不会得到相同的答案。
>>> j = np.asarray(i)
>>> x[j]
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]],
...,
[[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]],
[[18, 19, 20],
[21, 22, 23],
[24, 25, 26]],
[[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8]],
[[ 9, 10, 11],
[12, 13, 14],
[15, 16, 17]]]])
Why is this so? 为什么会这样呢? Why can't I use NumPy arrays as indices to NumPy array? 为什么不能将NumPy数组用作NumPy数组的索引?
x[j]
is the equivalent of x[j,:,:]
x[j]
等于x[j,:,:]
In [163]: j.shape
Out[163]: (3, 4)
In [164]: x[j].shape
Out[164]: (3, 4, 3, 3)
The resulting shape is the shape of j
joined with the last 2 dimensions of x
. 生成的形状是j
的形状,并与x
的最后2个维度相连。 j
just selects from the 1st dimension of x
. j
只是从x
的第一维中选择。
x[i]
on the other hand, is the equivalent to x[tuple(i)]
, that is: 另一方面, x[i]
等效于x[tuple(i)]
,即:
In [168]: x[[0, 1, 2, 1], [2, 1, 0, 1], [1, 2, 0, 1]]
Out[168]: array([ 7, 14, 18, 13])
In fact x(tuple(j)]
produces the same 4 item array. 实际上x(tuple(j)]
会产生相同的4项数组。
The different ways of indexing numpy arrays can be confusing. 索引numpy数组的不同方法可能会造成混淆。
Another example of how the shape of the index array or lists affects the output: 索引数组或列表的形状如何影响输出的另一个示例:
In [170]: x[[[0, 1], [2, 1]], [[2, 1], [0, 1]], [[1, 2], [0, 1]]]
Out[170]:
array([[ 7, 14],
[18, 13]])
Same items, but in a 2d array. 相同的项目,但为二维数组。
Check out the docs for numpy , what you are doing is "Integer Array Indexing", you need to pass each coordinate in as a separate array: 签出numpy的文档 ,您正在做的是“整数数组索引”,您需要将每个坐标作为单独的数组传递:
j = [np.array(x) for x in i]
x[j]
Out[191]: array([ 7, 14, 18, 13])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.