2012-11-20 29 views
2

我有關於如何從一個2D numpy的陣列numpy的定製陣列元件檢索

Foo = 
array([[ 1, 2, 3], 
     [ 4, 5, 6], 
     [ 7, 8, 9], 
     [10, 11, 12]]) 

Bar = 
array([[0, 0, 1], 
     [1, 2, 3]]) 

我想提取使用欄的值作爲索引,從富元件,使得我最終提取特定值的一個問題具有與Bar相同形狀的2D矩陣/陣列Baz。在Baz所對應的i列亞Foo[(np.array(each j in Bar[:,i]),np.array(i,i,i,i ...))]

Baz = 
array([[ 1, 2, 6], 
     [ 4, 8, 12]]) 

我可以做嵌套for循環,但我不知道是否有一個更優雅,numpy的上下的方式做到這一點一對夫婦。

對不起,如果這有點複雜。讓我知道是否需要進一步解釋。

謝謝!

回答

2

您可以使用Bar作爲行索引和列索引的數組[0, 1, 2]

# for easy copy-pasting 
import numpy as np 
Foo = np.array([[ 1, 2, 3], [ 4, 5, 6], [ 7, 8, 9], [10, 11, 12]]) 
Bar = np.array([[0, 0, 1], [1, 2, 3]]) 

# now use Bar as the `i` coordinate and 0, 1, 2 as the `j` coordinate: 

Foo[Bar, [0, 1, 2]] 
# array([[ 1, 2, 6], 
#  [ 4, 8, 12]]) 

# OR, to automatically generate the [0, 1, 2] 

Foo[Bar, xrange(Bar.shape[1])] 
+0

謝謝!它的作品非常漂亮。我會盡快接受 – ejang