用 2d 数组索引 3d numpy 数组 [英] Indexing of 3d numpy arrays with 2d arrays
问题描述
我正在尝试从 3d numpy 数组中提取值.目前我可以执行以下操作:
I am attempting to extract values from a 3d numpy array. At the moment I can perform the following operations:
newmesh.shape
(40,40,40)
newmesh[2,5,6]
6
然而,如果我尝试用数组索引它,结果并不如预期;
However, if I try to index it with an array, the result is not as expected;
newmesh[np.array([2,5,6])].shape
(3, 42, 42)
我曾尝试使用 np.take,但它会产生以下结果;
I have tried using np.take, however it produces the following;
np.take(newmesh,np.array([2,5,6]))
[-1 -1 -1]
任何想法为什么会发生这种情况?我的目标是输入一个 (n,3) 数组,其中每一行对应一个 newmesh 的值,即输入一个 (n,3) 数组将返回一个长度为 n 的一维数组.
Any ideas why this is happening? My goal is to input a (n,3) array, where each row corresponds to a value of newmesh, i.e. inputting a (n,3) array would give back a 1d array of length n.
推荐答案
使用 idx
作为 (n,3)
索引数组,一种使用 linear 的方法-indexing
将与 np.ravel_multi_index
-
With idx
as the (n,3)
indexing array, one approach using linear-indexing
would be with np.ravel_multi_index
-
np.take(newmesh,np.ravel_multi_index(idx.T,newmesh.shape))
元组形成的方法看起来像这样 -
An approach with tuple formation would look like this -
newmesh[tuple(idx.T)]
如果只有三个维度,你甚至可以只使用柱状切片来索引每个维度,就像这样 -
If there are just three dimensions, you can even just use columnar slices for indexing into each dimension, like so -
newmesh[idx[:,0],idx[:,1],idx[:,2]]
运行时测试如果有人有兴趣查看与所列方法相关的性能数据,这里有一个快速运行时测试 -
Runtime test If anyone's interested in seeing the performance numbers associated with the listed approaches, here's a quick runtime test -
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
这篇关于用 2d 数组索引 3d numpy 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!