numpy数组索引:list index和np.array index给出不同的结果 [英] numpy array indexing: list index and np.array index give different result
问题描述
我正在尝试使用list和 np.array
索引索引np.array。但他们给出了不同的结果。
I am trying to index an np.array using list and np.array
indexes. But they give different result.
这是一个例子:
import numpy as np
x = np.arange(10)
idx = [[0, 1], [1, 2]]
x[np.array(idx)] # returns array([[0, 1], [1, 2]])
但直接应用列表给出错误
but straightly apply the list gives error
x[idx] # raises IndexError: too many indices for array
我期望上面的返回与使用 np.array
索引的结果相同。
任何想法为什么?
I'm expecting the above returns the same result as using np.array
index.
Any ideas why?
我正在使用 python 3.5
和 numpy 1.13 .1
。
推荐答案
如果它是一个数组,它被解释为包含索引的最终数组的形状 - 但如果它是一个列表,它就是维度(多维数组索引)的索引。
If it's an array it's interpreted as shape of the final array containing the indices - but if it's an list it's the indices along the "dimensions" (multi-dimensional array indices).
所以第一个例子(带有数组
)相当于:
So the first example (with an array
) is equivalent to:
[[x[0], x[1],
[x[1], x[2]]
但是第二个例子( list
)被解释为:
But the second example (list
) is interpreted as:
[x[0, 1], x[1, 2]]
但是 x [0,1]
给出 IndexError:数组
的索引太多,因为 x
只有一个维度。
But x[0, 1]
gives a IndexError: too many indices for array
because your x
has only one dimension.
这是因为 list
被解释为它是一个元组,与单独传递它们相同: / p>
That's because list
s are interpreted like it was a tuple, which is identical to passing them in "separately":
x[[0, 1], [1, 2]]
^^^^^^----- indices for the second dimension
^^^^^^------------- indices for the first dimension
这篇关于numpy数组索引:list index和np.array index给出不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!