Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.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数组与二维数组的索引_Python_Arrays_Numpy - Fatal编程技术网

Python 三维numpy数组与二维数组的索引

Python 三维numpy数组与二维数组的索引,python,arrays,numpy,Python,Arrays,Numpy,我正在尝试从3d numpy数组中提取值。目前,我可以执行以下操作: newmesh.shape (40,40,40) newmesh[2,5,6] 6 但是,如果我尝试用数组对它进行索引,结果就不符合预期 newmesh[np.array([2,5,6])].shape (3, 42, 42) 我尝试过使用np.take,但是它会产生以下结果: np.take(newmesh,np.array([2,5,6])) [-1 -1 -1] 知道为什么会这样吗?我的目标是输入一个(n,3)数

我正在尝试从3d numpy数组中提取值。目前,我可以执行以下操作:

newmesh.shape
(40,40,40)

newmesh[2,5,6]
6
但是,如果我尝试用数组对它进行索引,结果就不符合预期

newmesh[np.array([2,5,6])].shape
(3, 42, 42)
我尝试过使用np.take,但是它会产生以下结果:

np.take(newmesh,np.array([2,5,6]))
[-1 -1 -1]

知道为什么会这样吗?我的目标是输入一个(n,3)数组,其中每行对应一个newmesh值,即输入一个(n,3)数组将返回一个长度为n的1d数组。

使用
idx
作为
(n,3)
索引数组,使用
线性索引的一种方法是-

具有元组形成的方法如下所示-

newmesh[tuple(idx.T)]
如果只有三个维度,您甚至可以使用柱状切片对每个维度进行索引,如下所示-

newmesh[idx[:,0],idx[:,1],idx[:,2]]
运行时测试如果有人想查看与列出的方法相关的性能数据,这里有一个快速的运行时测试-

In [18]: newmesh = np.random.rand(40,40,40)

In [19]: idx = np.random.randint(0,40,(1000,3))

In [20]: %timeit np.take(newmesh,np.ravel_multi_index(idx.T,newmesh.shape))
10000 loops, best of 3: 22.5 µs per loop

In [21]: %timeit newmesh[tuple(idx.T)]
10000 loops, best of 3: 20.9 µs per loop

In [22]: %timeit newmesh[idx[:,0],idx[:,1],idx[:,2]]
100000 loops, best of 3: 17.2 µs per loop

谢谢,这很有帮助。你知道为什么我做的不正确吗?@Jack Well没有任何逗号,在NumPy数组中,你只是用
newmesh[np.array([2,5,6])]
之类的东西索引到第一个dim,它会从第一个dim中选择三个元素,从其余dim中选择所有元素。因此,它本质上是:
newmesh[np.array([2,5,6]),:,:]
In [18]: newmesh = np.random.rand(40,40,40)

In [19]: idx = np.random.randint(0,40,(1000,3))

In [20]: %timeit np.take(newmesh,np.ravel_multi_index(idx.T,newmesh.shape))
10000 loops, best of 3: 22.5 µs per loop

In [21]: %timeit newmesh[tuple(idx.T)]
10000 loops, best of 3: 20.9 µs per loop

In [22]: %timeit newmesh[idx[:,0],idx[:,1],idx[:,2]]
100000 loops, best of 3: 17.2 µs per loop