2012-09-21 41 views
1

我試圖從數組中返回一個(方形)節,其中索引環繞着邊。我需要處理一些索引,但是它起作用,但是,我希望最後兩行代碼具有相同的結果,爲什麼他們不? numpy如何解釋最後一行?使用數組的Numpy索引

作爲一個額外的問題:我是用這種方法效率低下嗎?我使用的是product,因爲我需要對範圍進行取模,所以它會環繞,否則我會使用a[imin:imax, jmin:jmax, :],當然。

import numpy as np 
from itertools import product 

i = np.arange(-1, 2) % 3 
j = np.arange(1, 4) % 3 

a = np.random.randint(1,10,(3,3,2)) 

print a[i,j,:] 
# Gives 3 entries [(i[0],j[0]), (i[1],j[1]), (i[2],j[2])] 
# This is not what I want... 

indices = list(product(i, j)) 
print indices 

indices = zip(*indices) 

print 'a[indices]\n', a[indices] 
# This works, but when I'm explicit: 
print 'a[indices, :]\n', a[indices, :] 
# Huh? 

回答

3

的問題是,advanced indexing被觸發,如果:

選擇對象,OBJ,是[...]與至少一種序列對象或ndarray元組

的最簡單的修復方法是使用重複索引:

a[i][:, j] 

另一種方法是使用ndarray.take,如果指定mode='wrap'這會爲您執行模操作:

a.take(np.arange(-1, 2), axis=0, mode='wrap').take(np.arange(1, 4), axis=1, mode='wrap') 
3

爲了讓先進的索引是在那麼我看來product更好的解決方案的另一種方法。

如果你對每一個維度的整數數組這些廣播一起輸出作爲廣播形狀相同的輸出(你會明白我的意思)......

i, j = np.ix_(i,j) # this adds extra empty axes 

print i,j 

print a[i,j] 
# and now you will actually *not* be surprised: 
print a[i,j,:] 

注意,這是一個3x3x2陣列,而你有一個9x2陣列,但簡單的重塑會解決這個問題,3x3x2陣列實際上更接近你想要的。

其實驚喜仍然隱藏的方式,因爲在你的例子a[indices]相同​​但a[indicies,:]a[(indicies[0], indicies[1]),:]這是不是一個巨大的驚喜,這是不同的。請注意,a[indicies[0], indicies[1],:]確實會給出相同的結果。