2017-05-03 72 views
0

假設我有以下數組。Numpy:使用不同索引數組多次選擇行

l = np.asarray([1,3,5,7]) 

Out[552]: array([1, 3, 5, 7]) 

我可以使用索引陣列np.asarray([[0,1],[1,2]])兩次選擇行:

l[np.asarray([[0,1],[1,2]])] 
Out[553]: 
array([[1, 3], 
     [3, 5]]) 

如果指數陣列對各行不同長度的它不工作:

l[np.asarray([[1,3],[1,2,3]])] 

Traceback (most recent call last): 

    File "<ipython-input-555-3ec2ab141cd4>", line 1, in <module> 
    l[np.asarray([[1,3],[1,2,3]])] 
IndexError: arrays used as indices must be of integer (or boolean) type 

我本例所需的輸出爲:

array([[3, 7], 
     [3, 5, 7]]) 

有人可以幫忙嗎?

+0

numpy的不支持破​​爛(非矩形陣列),所以你可能要考慮,你可以用它來存儲您的輸出(如表)的其它數據的。 – DSM

回答

0

如果您單獨構建列表,您可以獲得後面的結果。

代碼:

l = np.asarray([1, 3, 5, 7]) 

# Build a sample array 
print(np.array([[3, 7], [3, 5, 7]])) 

# do the lookups into the original array 
print(np.array([list(l[[1, 3]]), list(l[[1, 2, 3]])])) 

結果:

[[3, 7] [3, 5, 7]] 
[[3, 7] [3, 5, 7]] 
+0

感謝您的答案,但我的索引數組有很多行,這種方法不會縮放。 – Allen

+1

@艾倫,通常是把這些細節放入問題中的好主意,而且以後不會留下驚喜。 –

1

我覺得這是最接近我可以得到的。

import numpy as np 
l = np.asarray([1, 3, 5, 7]) 
idx = [[1,3],[1,2,3]] 
output = np.array([np.array(l[i]) for i in idx]) 
print output 

結果:

[array([3, 7]) array([3, 5, 7])] 
+0

謝謝。這更接近。如果Numpy不支持@DSM提到的不規則陣列,也許它不會變得更好。 – Allen

+0

是的,我認爲'list'對於這樣的索引更好。 –