用元组列表索引一个numpy数组 [英] Indexing a numpy array with a list of tuples
问题描述
为什么不能使用像这样的元组索引列表来对ndarray进行索引?
Why can't I index an ndarray using a list of tuple indices like so?
idx = [(x1, y1), ... (xn, yn)]
X[idx]
相反,我必须要做一些笨拙的事情
Instead I have to do something unwieldy like
idx2 = numpy.array(idx)
X[idx2[:, 0], idx2[:, 1]] # or more generally:
X[tuple(numpy.vsplit(idx2.T, 1)[0])]
有没有更简单,更Python化的方式?
Is there a simpler, more pythonic way?
推荐答案
您可以使用元组列表,但是约定与您想要的约定不同. numpy
需要一个行索引列表,然后是一个列值列表.显然,您希望指定(x,y)对的列表.
You can use a list of tuples, but the convention is different from what you want. numpy
expects a list of row indices, followed by a list of column values. You, apparently, want to specify a list of (x,y) pairs.
http://docs.scipy.org/doc/numpy /reference/arrays.indexing.html#integer-array-indexing 文档中的相关部分是整数数组索引".
http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#integer-array-indexing The relevant section in the documentation is 'integer array indexing'.
这里是一个示例,它在2d数组中寻找3个点. (在2d中2点可能会令人困惑):
Here's an example, seeking 3 points in a 2d array. (2 points in 2d can be confusing):
In [223]: idx
Out[223]: [(0, 1, 1), (2, 3, 0)]
In [224]: X[idx]
Out[224]: array([2, 7, 4])
使用您的xy对索引样式:
Using your style of xy pairs of indices:
In [230]: idx1 = [(0,2),(1,3),(1,0)]
In [231]: [X[i] for i in idx1]
Out[231]: [2, 7, 4]
In [240]: X[tuple(np.array(idx1).T)]
Out[240]: array([2, 7, 4])
X[tuple(zip(*idx1))]
是进行转换的另一种方法. tuple()
在Python2中是可选的. zip(*...)
是Python惯用语,可反转列表的嵌套.
X[tuple(zip(*idx1))]
is another way of doing the conversion. The tuple()
is optional in Python2. zip(*...)
is a Python idiom that reverses the nesting of a list of lists.
您在正确的轨道上:
In [242]: idx2=np.array(idx1)
In [243]: X[idx2[:,0], idx2[:,1]]
Out[243]: array([2, 7, 4])
我的tuple()
只是更紧凑(不一定是更多的"pythonic").根据numpy
约定,必须进行某种转换.
My tuple()
is just a bit more compact (and not necessarily more 'pythonic'). Given the numpy
convention, some sort of conversion is necessary.
(我们是否应该检查n维和m点有效的方法?)
(Should we check what works with n-dimensions and m-points?)
这篇关于用元组列表索引一个numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!