2012-11-19 160 views
6

如何根據索引公式「雕刻」或遮罩2D numpy數組?我不在乎元素值是什麼,只是它在數組中的位置。通過索引雕刻2D numpy數組

例如,給定一個的m×m陣列,如何抽取爲地址符合

for i in range(0,m): 
    for j in range(0,m): 
     if j-i-k>=0: 
      A[i,j] = 1 
     elif j-p-k>=0: 
      A[i,j] = 1 
     elif i-k>=0: 
      A[i,j] = 1 
     else: 
      A[i,j] = 0 
     j=j+1 
    i=i+1 

其中

k和p爲任意的柵欄的所有元素

假設

k<m 
p<m 

這最終看起來像一個對角切片+水平切片+ a垂直切片。沒有上面的for循環可以完成嗎?

+0

上NEW_DATA =數據[面具] @tcaswell,用我的「爲」創造面具「刪除」一些行和列更多的問題,在某種程度上給我留下了一個向量,而不是原始data.shape的數組。爲什麼?我怎樣才能防止這一點? – Hokiexterra

回答

1
xdim,ydim = data.shape 
k = 2 
a, b = np.meshgrid(range(ydim),range(xdim)) 
mask = (b - a -k) < 0 

new_data = data[mask] 

new_data2 = np.array(data) # to force a copy 
new_data2[~mask] = 0 

new_data是因爲掩蔽處理(完成這種方式)變平的陣列的載體。你正在選擇一個不能用數組表示的破舊的形狀。如果您只是想將非選擇的值設置爲0,請使用new_data2。

+0

關於 – Hokiexterra

+0

@ user1836722的更多問題請參閱編輯。 – tacaswell

+0

謝謝,我會試試! – Hokiexterra

3
In [1]: import numpy as np 

In [2]: k = 2 

In [3]: i, j = np.ogrid[0:5,0:5] 

In [4]: mask = (j-i-k < 0) 

In [5]: mask 
Out[5]: 
array([[ True, True, False, False, False], 
     [ True, True, True, False, False], 
     [ True, True, True, True, False], 
     [ True, True, True, True, True], 
     [ True, True, True, True, True]], dtype=bool) 

In [6]: mask.shape 
Out[6]: (5, 5) 

In [7]: mask.dtype 
Out[7]: dtype('bool') 
1

下面是使用np.indices另一種方式:

>>> import numpy as np 
>>> a = np.arange(90).reshape(10,9) 
>>> b = np.indices(a.shape) 
>>> k = 2 
>>> i = b[1] - b[0] - k 
>>> a[i < 0] 
array([ 0, 1, 9, 10, 11, 18, 19, 20, 21, 27, 28, 29, 30, 31, 36, 37, 38, 
    39, 40, 41, 45, 46, 47, 48, 49, 50, 51, 54, 55, 56, 57, 58, 59, 60, 
    61, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 
    79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89]) 
+0

+1,因爲我學到了一些東西 – tacaswell