[英]numpy array indexing: list index and np.array index give different result
I am trying to index an np.array using list and np.array
indexes. 我正在尝试使用列表和
np.array
索引来索引np.array
。 But they give different result. 但是他们给出了不同的结果。
Here is an illustration: 这是一个例子:
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
I'm expecting the above returns the same result as using np.array
index. 我期望上面的返回与使用
np.array
索引相同的结果。 Any ideas why? 有什么想法吗?
I am using python 3.5
and numpy 1.13.1
. 我正在使用
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: 因此,第一个示例(带有
array
)等效于:
[[x[0], x[1],
[x[1], x[2]]
But the second example ( list
) is interpreted as: 但是第二个示例(
list
)被解释为:
[x[0, 1], x[1, 2]]
But x[0, 1]
gives a IndexError: too many indices for array
because your x
has only one dimension. 但是
x[0, 1]
给出了IndexError: too many indices for array
因为您的x
只有一个维。
That's because list
s are interpreted like it was a tuple, which is identical to passing them in "separately": 这是因为
list
的解释就像是一个元组,等同于“单独”传递它们:
x[[0, 1], [1, 2]] ^^^^^^----- indices for the second dimension ^^^^^^------------- indices for the first dimension
From numpy indexing documentation: 从numpy索引文档中:
ndarrays can be indexed using the standard Python
x[obj]
syntax, wherex
is the array andobj
the selection.可以使用标准Python
x[obj]
语法对ndarrays进行索引,其中x
是数组,而obj
是选择。...
...
Basic slicing occurs when obj is a slice object (constructed bystart:stop:step
notation inside of brackets), an integer, or a tuple ofslice
objects and integers.当obj是一个切片对象(由方括号内的
start:stop:step
表示法构造),整数或slice
对象和整数的元组时,将发生基本切片。Ellipsis
andnewaxis
objects can be interspersed with these as well.Ellipsis
和newaxis
对象也可以散布在这些对象上。 In order to remain backward compatible with a common usage in Numeric, basic slicing is also initiated if the selection object is any non-ndarray sequence (such as alist
) containingslice
objects, theEllipsis
object, or thenewaxis
object, but not for integer arrays or other embedded sequences .为了保持向后兼容的数字共同使用,基本切片也发起如果选择对象是任何非ndarray序列(如
list
)含有slice
目的,Ellipsis
对象,或newaxis
对象,但不为整数数组或其他嵌入序列 。 ......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.