numpy:索引3D数组,将最后一个轴的索引存储在2D数组中 [英] Numpy: Index 3D array with index of last axis stored in 2D array

查看:82
本文介绍了numpy:索引3D数组,将最后一个轴的索引存储在2D数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的ndarrayshape(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_indicesval_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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆