2010-02-21 55 views
1

目前我有一個代碼檢查數組中的給定元素是否等於0,如果是,則將值設置爲'level'值(temp_board是2D numpy數組,indices_to_watch包含應該觀察的2D座標爲零)。Numpy masked array modification

indices_to_watch = [(0,1), (1,2)] 
    for index in indices_to_watch: 
     if temp_board[index] == 0: 
      temp_board[index] = level 

我想這個轉換爲更numpy的類似方法(去掉了,並且只使用numpy的功能),以加快這。 這裏是我的嘗試:

masked = np.ma.array(temp_board, mask=(a!=0), hard_mask=True) 
    masked.put(indices_to_watch, level) 

但不幸的是掩蓋陣列在做把()希望有一維的尺寸(完全陌生的!),有沒有更新是等於0,並有具體的數組元素的一些其他的方式指數?

或者,也許使用屏蔽陣列是不是要走的路?

回答

1

假設它是不是很低效,找出temp_board0,你可以做你想做這樣的東西:

# First figure out where the array is zero 
zindex = numpy.where(temp_board == 0) 
# Make a set of tuples out of it 
zindex = set(zip(*zindex)) 
# Make a set of tuples from indices_to_watch too 
indices_to_watch = set([(0,1), (1,2)]) 
# Find the intersection. These are the indices that need to be set 
indices_to_set = indices_to_watch & zindex 
# Set the value 
temp_board[zip(*indices_to_set)] = level 

如果不能做到以上,那麼這裏有一個這樣,但我不知道這是否是最Python化:

indices_to_watch = [(0,1), (1,2)] 

首先,轉換爲numpy的數組:

indices_to_watch = numpy.array(indices_to_watch) 

然後,使其可轉位:

index = zip(*indices_to_watch) 

然後,測試條件:

indices_to_set = numpy.where(temp_board[index] == 0) 

然後,計算出實際的指標設置:

final_index = zip(*indices_to_watch[indices_to_set]) 

最後,設置值:

temp_board[final_index] = level 
+0

謝謝:) 我試過numpy.where()但沒想到將它與set set intersection – 2010-02-23 12:27:41

0

你應該嘗試的東西沿着這些線路:

temp_board[temp_board[field_list] == 0] = level 
+0

不幸的是temp_board [field_list] == 0返回一個小於temp_board的大小的掩碼 – 2010-02-21 19:34:13

1

我不知道我遵循所有的細節在你的問題。如果我理解正確,那麼看起來這是直接的Numpy索引。下面的代碼檢查數組(A)是否爲​​零,以及它在哪裏找到它們,它將它們替換爲'level'。

import numpy as NP 
A = NP.random.randint(0, 10, 20).reshape(5, 4) 
level = 999 
ndx = A==0 
A[ndx] = level