如何有效地从numpy数组中提取由其索引给出的元素列表? [英] How to extract a list of elements given by their indices from a numpy array efficiently?

查看:1821
本文介绍了如何有效地从numpy数组中提取由其索引给出的元素列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个多维numpy数组,我想利用它的某些元素来构建一维数组.我需要采用的元素由它们的索引给出,例如:

I have a multidimensional numpy array and I would like to take some of its elements to construct a one dimensional array. The elements that I need to take are given by their indices, for example:

inds = [(0,0), (0,1), (1,1), (1,0), (0,2)] 

我以一种简单的方式解决它:

I solve it in a straightforward way:

ls = [] 
for i, j in inds:
   ls += [a[i,j]]

它给出期望的结果.但是,我已经意识到此解决方案对于我的目的而言太慢了.是否有可能以更有效的方式做同样的事情?

It gives the desired result. However, I have realized that this solution is too slow for my purposes. Are there a possibility to do the same in a more efficient way?

推荐答案

numpy数组可以用序列(通常是numpy数组)建立索引.

numpy arrays can be indexed with sequences (and, more generally, numpy arrays).

例如,这是我的数组a

In [19]: a
Out[19]: 
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14]])

ij保存inds数组的第一个和第二个坐标的序列:

i and j hold the sequences of the first and second coordinates of your inds array:

In [20]: i
Out[20]: [0, 0, 1, 1, 0]

In [21]: j
Out[21]: [0, 1, 1, 0, 2]

您可以使用它们从a中拉出相应的值:

You can use these to pull the corresponding values out of a:

In [22]: a[i, j]
Out[22]: array([0, 1, 6, 5, 2])

如果代码中已经包含inds,则可以使用zip将元组列表分为ij:

If you already have inds in your code, you can separate the list of tuples into i and j using zip:

In [23]: inds
Out[23]: [(0, 0), (0, 1), (1, 1), (1, 0), (0, 2)]

In [24]: i, j = zip(*inds)

In [25]: i
Out[25]: (0, 0, 1, 1, 0)

In [26]: j
Out[26]: (0, 1, 1, 0, 2)

或者,如果inds是形状为(n,2)的数组,如下所示:

Or, if inds is an array with shape (n, 2), like so:

In [27]: inds = np.array(inds)

In [28]: inds
Out[28]: 
array([[0, 0],
       [0, 1],
       [1, 1],
       [1, 0],
       [0, 2]])

您可以简单地将inds的转置分配给i, j:

you can simply assign the transpose of inds to i, j:

In [33]: i, j = inds.T

In [34]: i
Out[34]: array([0, 0, 1, 1, 0])

In [35]: j
Out[35]: array([0, 1, 1, 0, 2])

In [36]: a[i, j]
Out[36]: array([0, 1, 6, 5, 2])

这篇关于如何有效地从numpy数组中提取由其索引给出的元素列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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