Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/335.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python numpy数组索引:列表索引和np.array索引给出不同的结果_Python_Arrays_Numpy_Indexing - Fatal编程技术网

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

Python numpy数组索引:列表索引和np.array索引给出不同的结果,python,arrays,numpy,indexing,Python,Arrays,Numpy,Indexing,我正在尝试使用list和np.array索引为np.array编制索引。但它们给出了不同的结果 下面是一个例子: import numpy as np x = np.arange(10) idx = [[0, 1], [1, 2]] x[np.array(idx)] # returns array([[0, 1], [1, 2]]) 但直接应用列表会产生错误 x[idx] # raises IndexError: too many indices for array 我希望上面的返回结

我正在尝试使用list和
np.array
索引为np.array编制索引。但它们给出了不同的结果

下面是一个例子:

import numpy as np 
x = np.arange(10)
idx = [[0, 1], [1, 2]]
x[np.array(idx)]  # returns array([[0, 1], [1, 2]])
但直接应用列表会产生错误

x[idx]  # raises IndexError: too many indices for array
我希望上面的返回结果与使用
np.array
index相同。 你知道为什么吗


我使用的是
Python3.5
numpy 1.13.1

如果它是一个数组,它被解释为包含索引的最终数组的形状-但是如果它是一个列表,它是沿着“维度”(多维数组索引)的索引

因此,第一个示例(使用
数组
)相当于:

[[x[0], x[1],
 [x[1], x[2]]
但第二个示例(
列表
)被解释为:

[x[0, 1], x[1, 2]]
但是
x[0,1]
给出了一个
索引器错误:数组的索引太多,因为
x
只有一个维度

这是因为
list
s被解释为一个元组,这与“分别”传递它们是一样的:

x[[0,1],[1,2]] ^^^^^^-----第二维度的指数 ^^^^^^-------------第一维指数 从文档:

ndarrays可以使用标准Python
x[obj]
语法编制索引,其中
x
是数组,
obj
是选择


当obj是切片对象(由
start:stop:step
括号内的符号)、整数或元组 对象和整数的切片<代码>省略号
新建轴
对象可以是 也点缀着这些。为了保持落后, 与数字中的常见用法兼容,还可以使用基本切片 如果选择对象是任何非ndarray序列(例如 一个
列表
),包含
切片
对象、
省略号
对象或
新轴
对象,但不适用于整数数组或其他嵌入序列


列表被视为元组,但问题中的两个示例都不会触发基本的切片。数组触发高级索引,列表触发不同的高级索引,原因文档没有充分解释。在numpy 1.15中,第二种情况将发出警告,要求您澄清是指
x[tuple(idx)]
还是
x[np.array(idx)]
x[[0, 1], [1, 2]] ^^^^^^----- indices for the second dimension ^^^^^^------------- indices for the first dimension