2017-07-18 64 views
1

I獲得具有三維numpy的陣列和我獲得滿足一定的條件的索引的索引,例如:應用偏移從np.where

a = np.tile([[1,2],[3,4]],(2,2,2)) 
indices = np.where(a == 2) 

向該指數,我需要應用偏移量,例如(0,0,1),並查看是否符合其他條件。

事情是這樣的:

offset = [0, 0, 1] 
indices_shift = indices + offset 

count = 0 
for i in indices_shift: 
    if a[i] == 3: 
     count += 1 

在這個例子中,與膠印的(0,0,1),該指數的樣子:

indices = (array([0, 0, 0, 0, 1, 1, 1, 1], dtype=int64), array([0, 0, 2, 2, 0, 0, 2, 2], dtype=int64), array([1, 3, 1, 3, 1, 3, 1, 3], dtype=int64)) 

,我認爲加偏移結果應該是這樣的:

indices_shift = (array([0, 0, 0, 0, 1, 1, 1, 1], dtype=int64), array([0, 0, 2, 2, 0, 0, 2, 2], dtype=int64), array([2, 4, 2, 4, 2, 4, 2, 4], dtype=int64)) 

有沒有簡單的方法來做到這一點?

謝謝。

+1

你是什麼意思的「轉變」?按照[mcve]提問時,試着給出預期的輸出。 –

+0

按班次我的意思是抵消。在這個例子中,我想將1添加到最後一個維度。我會盡力澄清這個問題。 – Greynes

+0

移位索引超出範圍時,預期輸出是多少? –

回答

1

這裏有一個方法 -

idx = np.argwhere(a == 2)+[0,0,1] 
valid_mask = (idx< a.shape).all(1) 
valid_idx = idx[valid_mask] 
count = np.count_nonzero(a[tuple(valid_idx.T)] == 3) 

步驟:

  • 獲取指數對2匹配。在這裏使用np.argwhere來獲得一個漂亮的2D數組,每列代表一個軸。另一個好處是這使得通用處理具有一般維數的數組。然後,以廣播的方式添加offset。這是idx

  • idx的索引中,幾乎沒有超出數組形狀的無效索引。所以,得到一個有效的掩碼valid_mask,因此其中有效索引valid_idx

  • 最後用這些數組索引到輸入數組中,並與3進行比較並計算匹配數。