numpy的Mutidimensional子集 [英] Numpy Mutidimensional Subsetting
问题描述
我已经搜索漫长而艰难的一个回答这个问题,但没有发现任何东西,非常适合该法案。我有一个多维numpy的包含数组数据(在我的情况3维)以及包含在我沿着原始数组的最后一维想要的价值信息的另一个阵列(2维)。例如,这里是示出该问题的简单的例子。我有数据 A
的数组,另一个数组 B
含指数沿尺寸2一个
。我想要一个新的二维数组 C
,其中 C [I,J] = A [I,J,B [I,J]]
。唯一我能想到这样做是一个循环,概述如下方式。然而,这似乎笨重而缓慢。
I have searched long and hard for an answer to this question, but haven't found anything that quite fits the bill. I have a multidimensional numpy array containing data (in my case 3 dimensional) and another array (2 dimensional) that contains information on which value I want along the last dimension of the original array. For instance, here is a simple example illustrating the problem. I have an array a
of data, and another array b
containing indices along dimension 2 of a
. I want a new two dimensional array c
where c[i, j] = a[i, j, b[i, j]]
.The only way that I can think to do it is with a loop, as outlined below. However, this seems clunky and slow.
In [3]: a = np.arange(8).reshape((2, 2, 2))
In [4]: a
Out[4]:
array([[[0, 1],
[2, 3]],
[[4, 5],
[6, 7]]])
In [6]: b = np.array([[0, 1], [1, 1]])
In [8]: c = np.zeros_like(b)
In [9]: for i in xrange(2):
...: for j in xrange(2):
...: c[i, j] = a[i, j, b[i, j]]
In [10]: c
Out[10]:
array([[0, 3],
[5, 7]])
是否有这样做的更pythonic的方法,或许有些numpy的索引功能,其中我不知道?
Is there a more pythonic way of doing this, perhaps some numpy indexing feature of which I am unaware?
推荐答案
当你看中指数与多维数组多维数组,每个维度的指标被广播在一起。考虑到这一点,你可以这样做:
When you fancy-index a multidimensional array with multidimensional arrays, the indices for each dimension are broadcasted together. With that in mind, you can do:
>>> rows = np.arange(a.shape[0])
>>> cols = np.arange(a.shape[1])
>>> a[rows[:, None], cols, b]
array([[0, 3],
[5, 7]])
这篇关于numpy的Mutidimensional子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!