[英]Selecting multiple values from 3d numpy in efficient way
I have a very large 3d numpy from which I want to extract many values (x, y, z).我有一个非常大的 3d numpy,我想从中提取许多值(x、y、z)。
For the sake of simplicity let's say this is the numpy:为了简单起见,我们假设这是 numpy:
import numpy as np
a = np.arange(64).reshape(4,4,4)
From which I want to extract the values of the following collection of points:我想从中提取以下点集合的值:
points = [[3,0,0],[0,1,0],[3,0,1],[2,3,1]]
In this example, the expected result should be:在这个例子中,预期的结果应该是:
[48,4,49,45]
Because performance metter, I want to avoid iterate like the following code:因为性能计,我想避免像下面的代码那样迭代:
points = [[3,0,0],[0,1,0],[3,0,1],[2,3,1]]
for i in points:
print(a[i[0],i[1],i[2]])
Try this.尝试这个。 Uses numpy fancy/advanced indexing .使用 numpy 花式/高级索引。
>>> import numpy as np
>>> a = np.arange(64).reshape(4,4,4)
>>> points = [[3,0,0],[0,1,0],[3,0,1],[2,3,1]]
>>> points = np.array(points)
>>> i = points[:, 0]
>>> j = points[:, 1]
>>> k = points[:, 2]
>>> a[i, j, k]
array([48, 4, 49, 45])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.