2010-02-21 53 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