【问题标题】:How to invert numpy.where (np.where) function如何反转 numpy.where (np.where) 函数
【发布时间】:2012-03-19 04:45:09
【问题描述】:

我经常使用 numpy.where 函数来收集具有某些属性的矩阵的索引元组。例如

import numpy as np
X = np.random.rand(3,3)
>>> X
array([[ 0.51035326,  0.41536004,  0.37821622],
   [ 0.32285063,  0.29847402,  0.82969935],
   [ 0.74340225,  0.51553363,  0.22528989]])
>>> ix = np.where(X > 0.5)
>>> ix
(array([0, 1, 2, 2]), array([0, 2, 0, 1]))

ix 现在是包含行和列索引的 ndarray 对象的元组,而子表达式 X>0.5 包含一个布尔矩阵,指示哪些单元格具有 >0.5 属性。每种表示都有自己的优势。

获取 ix 对象并稍后在需要时将其转换回布尔形式的最佳方法是什么?例如

G = np.zeros(X.shape,dtype=np.bool)
>>> G[ix] = True

有没有完成同样事情的单线?

【问题讨论】:

    标签: python numpy boolean where indices


    【解决方案1】:

    可能是这样的吗?

    mask = np.zeros(X.shape, dtype='bool')
    mask[ix] = True
    

    但如果是像 X > 0 这样简单的东西,你可能最好使用 mask = X > 0,除非 mask 非常稀疏或者你不再引用 X

    【讨论】:

      【解决方案2】:
      mask = X > 0
      imask = np.logical_not(mask)
      

      例如

      编辑:抱歉之前这么简洁。不应该在电话里接电话:P

      正如我在示例中所指出的,最好只反转布尔掩码。比从where 的结果返回更有效/更容易。

      【讨论】:

        【解决方案3】:

        np.where 文档字符串的底部建议为此使用np.in1d

        >>> x = np.array([1, 3, 4, 1, 2, 7, 6])
        >>> indices = np.where(x % 3 == 1)[0]
        >>> indices
        array([0, 2, 3, 5])
        >>> np.in1d(np.arange(len(x)), indices)
        array([ True, False,  True,  True, False,  True, False], dtype=bool)
        

        (虽然这是一个不错的单线,但它比@Bi Rico 的解决方案慢很多。)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-01-17
          • 1970-01-01
          相关资源
          最近更新 更多