简体   繁体   English

Numpy:多个数组的花式索引

[英]Numpy: Fancy Indexing over Multiple arrays

Is there an efficient way to index over multiple arrays? 有没有一种有效的方法来索引多个数组?

For example, I have an array I want to index from 例如,我有一个我想索引的数组

a = [[1,2,3],[4,5,6]]

And another array contains the indices. 另一个数组包含索引。 b = [[0, 1], [1,2]]

And I expect [[1, 2], [5, 6]] , which indexes the first row of a by [0,1] , and indexes the second row of a by [1,2] . 我期望[[1, 2], [5, 6]]其指数的第一行的a[0,1]和索引的第二行a[1,2]

Thanks. 谢谢。

If a and b are of same length, may be you can try using np.take as following: 如果ab的长度相同,可以尝试使用np.take如下:

import numpy as np

a = [[1,2,3],[4,5,6]]
b = [[0, 1], [1,2]]
result = [np.take(a[i],b[i]).tolist() for i in range(len(a))]

print(result)
# result: [[1, 2], [5, 6]]
In [107]: a = [[1,2,3],[4,5,6]]
In [108]: b = [[0, 1], [1,2]]

a and b are lists. ab是列表。 The appropriate solution is a nested list comprehension 适当的解决方案是嵌套列表理解

In [111]: [[a[i][j] for j in x] for i,x in enumerate(b)]
Out[111]: [[1, 2], [5, 6]]

Now if a is made into a numpy array: 现在,如果a成为一个numpy数组:

In [112]: np.array(a)[np.arange(2)[:,None], b]
Out[112]: 
array([[1, 2],
       [5, 6]])

For this the 1st dimension of the array is indexed with a (2,1) array, and the 2nd with a (2,2). 为此,数组的第一维用(2,1)数组索引,第二维用(2,2)索引。 They broadcast together to produce a (2,2) result. 他们一起播放产生(2,2)结果。

Numpy extract submatrix Numpy提取子矩阵

is working in the same direction, but the accepted answer use ix_ 正在朝着同一个方向努力,但接受的答案使用ix_

Y[np.ix_([0,3],[0,3])]

which won't work in the case of a (2,2) b . 这对于(2,2) b的情况不起作用。

In [113]: np.array(a)[np.ix_(np.arange(2), b)]
ValueError: Cross index must be 1 dimensional

ix_ will turn the 1st dimension np.arange(2) in to the right (2,1). ix_将第一维np.arange(2)转到右边(2,1)。


This might make the broadcasting more explicit: 这可能会使广播更加明确:

In [114]: np.array(a)[[[0,0],[1,1]], [[0,1],[1,2]]]
Out[114]: 
array([[1, 2],
       [5, 6]])

It selects elements (0,0), (0,1), (1,1) and (1,2) 它选择元素(0,0),(0,1),(1,1)和(1,2)


To further test this, make b non symmetic: 为了进一步测试这个,使b非symmetic:

In [138]: b = [[0, 1,1], [1,2,0]]       # (2,3)
In [139]: np.array(a)[np.arange(2)[:,None], b]
Out[139]: 
array([[1, 2, 2],
       [5, 6, 4]])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM