多个索引的numpy数组替换为不同的矩阵 [英] Numpy array of multiple indices replace with a different matrix

查看:335
本文介绍了多个索引的numpy数组替换为不同的矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二维索引数组.

I have an array of 2d indices.

indices = [[2,4], [6,77], [102,554]]

现在,我有一个不同的4维数组arr,我只想提取一个在indexs数组中具有相应索引的数组(它是一个数组,因为它是4维).它等效于以下代码.

Now, I have a different 4-dimensional array, arr, and I want to only extract an array (it is an array, since it is 4-dimensional) with corresponding index in the indices array. It is equivalent to the following code.

for i in range(len(indices)):
    output[i] = arr[indices[i][0], indices[i][1]]

但是,我意识到使用显式的for循环会产生缓慢的结果.我可以使用任何内置的numpy API吗?在这一点上,我尝试使用np.choose,np.put,np.take,但没有成功产生我想要的东西.谢谢!

However, I realized that using explicit for-loop yields a slow result. Is there any built-in numpy API that I can utilized? At this point, I tried using np.choose, np.put, np.take, but did not succeed to yield what I wanted. Thank you!

推荐答案

我们需要使用索引中的两列来索引前两个轴(将其视为数组).

We need to index into the first two axes with the two columns from indices (thinking of it as an array).

因此,只需转换为数组和索引,就像这样-

Thus, simply convert to array and index, like so -

indices_arr = np.array(indices)
out = arr[indices_arr[:,0], indices_arr[:,1]]

或者我们可以直接提取它们而不转换为数组,然后索引-

Or we could extract those directly without converting to array and then index -

d0,d1 = [i[0] for i in indices], [i[1] for i in indices]
out = arr[d0,d1]

提取元素的另一种方法是将其转换为元组,就像这样-

Another way to extract the elements would be with conversion to tuple, like so -

out = arr[tuple(indices_arr.T)]

如果indices已经是数组,请跳过转换过程,并在有indices_arr的地方使用indices.

If indices is already an array, skip the conversion process and use indices in places where we had indices_arr.

这篇关于多个索引的numpy数组替换为不同的矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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