【问题标题】:Numpy masked array modificationNumpy 掩码数组修改
【发布时间】:2010-02-21 15:05:05
【问题描述】:

目前我有一个代码来检查数组中的给定元素是否等于 = 0,如果是,则将值设置为“级别”值(temp_board 是 2D numpy 数组,indices_to_watch 包含应该观察为零的二维坐标)。

    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() 想要有 1D 维度时被屏蔽的数组(完全奇怪!),是否有其他方法可以更新等于 0 并具有具体索引的数组元素?

或者也许使用掩码数组不是要走的路?

【问题讨论】:

    标签: python numpy masked-array


    【解决方案1】:

    假设找出temp_board在哪里0不是很低效,你可以像这样做你想做的事:

    # 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
    

    如果你不能做到以上,那么这里有一个方法,但我不确定它是否是最 Pythonic 的:

    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
    

    【讨论】:

    • 谢谢 :) 我试过 numpy.where() 但没有想到将它与 set intersection
    【解决方案2】:

    我不确定我是否遵循了您问题中的所有细节。如果我理解正确,那么这似乎是简单的 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
    

    【讨论】:

      【解决方案3】:

      你应该尝试这些方面的东西:

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

      【讨论】:

      • 不幸的是 temp_board[field_list] == 0 返回的掩码小于 temp_board 的大小
      猜你喜欢
      • 2020-02-29
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-03
      相关资源
      最近更新 更多