更新时间:2021-10-25 03:39:47
使用 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