2013-02-11 29 views
1
沒有被索引的數組引用的元素

說我有在Python的數組,例如:返回在Python

my_array = np.array([10, -5, 4, ...]) 
my_indices = np.array([0, 3, 10, ...]) 

我怎樣才能有效得到:

  1. 指數名單my_array不在my_indices
  2. 列表元素my_array引用由my_indices(瑣碎1,但也許有一個直接的方式)
+0

的問題是有點不清楚。如果您顯示每個問題的實際輸入和預期輸出,那麼它會更有用 – 2013-02-11 01:08:52

+0

可能的重複? http://stackoverflow.com/questions/8741445/better-way-to-use-index-array-to-get-elements/8741884#8741884 - 這個問題要求比前一個更多一點但是.. 。 – mgilson 2013-02-11 01:24:28

回答

5

我可能會做這樣的事情:

>>> import numpy as np 
>>> a = np.random.random(10) # set up a random array to play with 
>>> a 
array([ 0.20291643, 0.89973074, 0.14291639, 0.53535553, 0.21801353, 
     0.05582776, 0.64301145, 0.56081956, 0.85771335, 0.6032354 ]) 
>>> 
>>> b = np.array([0,5,6,9]) # indices we *don't want* 
>>> mask = np.ones(a.shape,dtype=bool) 
>>> mask[b] = False   # Converted to a mask array of indices we *do want* 
>>> mask 
array([False, True, True, True, True, False, False, True, True, False], dtype=bool) 
>>> 
>>> np.arange(a.shape[0])[mask] #This gets you the indices that aren't in your original 
array([1, 2, 3, 4, 7, 8]) 
>>> a[mask] #This gets you the elements not in your original. 
array([ 0.89973074, 0.14291639, 0.53535553, 0.21801353, 0.56081956, 
     0.85771335]) 
+0

我的感覺告訴我,這是所有答案中最有效的(我猜想索引比列表理解更「向量化」)。你怎麼看? – 2013-02-11 01:12:25

+1

@ user273158 - 可能還有更好的方法來做到這一點。實際上,你需要'時間'來確定你最好的選擇是什麼。 – mgilson 2013-02-11 01:13:14

2

對於部分1,你可以使用使用Python的built in set類兩組之間的差異。

my_array = [1,2,3,4] 
my_indices = [3,4,5] 

print list(set(my_array) - set(my_indices)) 

將輸出:[1, 2]


編輯

爲了回報指數的名單中my_array不在my_indices,你可以使用列表理解:

my_array = [1,2,3,4] 
my_indices = [0,3] 

print [x for x in range(len(my_array)) if x not in my_indices] 

也可表示爲:

temp = [] 
for x in range(len(my_array)): 
    if x not in my_indices: 
    temp.append(x) 

這將返回索引[1,2]

在你想獲得元素的列表,那麼你可以修改的語句是:

print [my_array[x] for x in range(len(my_array)) if x not in my_indices] 

將輸出[2,3]

+0

謝謝,但在我的第一個問題中,我正在尋找** my_array'的索引**,而不是它的元素,並且在我的第二個問題中,我正在尋找'my_indices'沒有引用**的元素。你的回答雖然可以解決另一個問題,但並沒有解決這些問題。 – 2013-02-11 01:02:14

+0

啊好的。我想我明白。我修改了我的答案。 – Th3Cuber 2013-02-11 01:30:17

1

對於第一個問題:

my_indices_set = set(my_indices) 
[i for i, x in enumerate(my_array) if i not in my_indices] 

對於第二個問題:

[x for x in my_array if x not in my_indices_set] 

這是更有效的,如果我們用套,但再有就是擺在首位

創建集的成本
1

您可以使用列表解析

array_len = len(my_array) 
missing_indices = [i for i in my_indices 
        if i < 0 or i >= array_len] 
elems = [my_array[i] for i in missing_indices]