简体   繁体   English

numpy数组索引:列表索引和np.array索引给出不同的结果

[英]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.5numpy 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, where x is the array and obj the selection. 可以使用标准Python x[obj]语法对ndarrays进行索引,其中x是数组,而obj是选择。

... ...
Basic slicing occurs when obj is a slice object (constructed by start:stop:step notation inside of brackets), an integer, or a tuple of slice objects and integers. 当obj是一个切片对象(由方括号内的start:stop:step表示法构造),整数或slice对象和整数的元组时,将发生基本切片。 Ellipsis and newaxis objects can be interspersed with these as well. Ellipsisnewaxis对象也可以散布在这些对象上。 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 a list ) containing slice objects, the Ellipsis object, or the newaxis object, but not for integer arrays or other embedded sequences . 为了保持向后兼容的数字共同使用,基本切片也发起如果选择对象是任何非ndarray序列(如list )含有slice目的, Ellipsis对象,或newaxis对象,但不为整数数组或其他嵌入序列 ... ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM