使用元组列表索引 numpy 数组 [英] Indexing a numpy array with a list of tuples

查看:37
本文介绍了使用元组列表索引 numpy 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我不能使用像这样的元组索引列表来索引 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])]

有没有更简单、更pythonic的方法?

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'.

这是一个示例,在二维数组中寻找 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屋!

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