当前,我有一个代码检查数组中给定的元素是否等于0,如果是,则将其值设置为“ level”值(temp_board为2D numpy数组,indexs_to_watch包含应注意为零的2D坐标)。

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


我想将其转换为更类似于numpy的方法(删除for,仅使用numpy函数)以加快此过程。
这是我尝试过的:

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


但是不幸的是,当进行put()操作时,被遮罩的数组想要具有一维尺寸(完全奇怪!),还有其他方法可以更新等于0并具有具体索引的数组元素吗?

也许不是使用遮罩数组?

最佳答案

假设找出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

关于python - numpy蒙版数组修改,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2306280/

10-14 10:02
查看更多