numpy:索引3D数组,将最后一个轴的索引存储在2D数组中 [英] Numpy: Index 3D array with index of last axis stored in 2D array
问题描述
我的ndarray
是shape(z,y,x)
,其中包含值.我试图用另一个shape(y,x)
的ndarray
对该数组建立索引,其中包含我感兴趣的值的z-index.
I have a ndarray
of shape(z,y,x)
containing values. I am trying to index this array with another ndarray
of shape(y,x)
that contains the z-index of the value I am interested in.
import numpy as np
val_arr = np.arange(27).reshape(3,3,3)
z_indices = np.array([[1,0,2],
[0,0,1],
[2,0,1]])
由于我的数组很大,因此我尝试使用np.take
避免不必要的数组副本,但无法用它索引3维数组.
Since my arrays are rather large I tried to use np.take
to avoid unnecessary copies of the array but just can't wrap my head around indexing 3-dimensional arrays with it.
如何用z_indices
索引val_arr
以获得所需z轴位置的值?预期结果将是:
How do I have to index val_arr
with z_indices
to get the values at the desired z-axis position? The expected outcome would be:
result_arr = np.array([[9,1,20],
[3,4,14],
[24,7,17]])
推荐答案
您可以使用 choose
进行选择:
You can use choose
to make the selection:
>>> z_indices.choose(val_arr)
array([[ 9, 1, 20],
[ 3, 4, 14],
[24, 7, 17]])
函数choose
非常有用,但要理解它可能有些棘手.本质上,给定一个数组(val_arr
),我们可以沿第一轴从每个n维切片中进行一系列选择(z_indices
).
The function choose
is incredibly useful, but can be somewhat tricky to make sense of. Essentially, given an array (val_arr
) we can make a series of choices (z_indices
) from each n-dimensional slice along the first axis.
此外:任何花式索引操作都会创建一个新数组,而不是原始数据的视图.如果不创建全新的数组,就无法使用z_indices
为val_arr
编制索引.
Also: any fancy indexing operation will create a new array rather than a view of the original data. It is not possible to index val_arr
with z_indices
without creating a brand new array.
这篇关于numpy:索引3D数组,将最后一个轴的索引存储在2D数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!