【问题标题】:Return the indices of "false" values in a boolean array返回布尔数组中“假”值的索引
【发布时间】:2022-01-01 11:58:09
【问题描述】:

我觉得这是一个非常简单的问题,但我找不到解决方案。

给定一个由真/假值组成的布尔数组,我需要所有值为“假”的索引的输出。我有办法做到这一点:

测试 = [真假真真]

test1 = np.where(test)[0]

这将返回 [0,2,3],即每个真值的对应索引。现在我需要为 false 得到同样的东西,输出将是 [1]。有人知道怎么做吗?

【问题讨论】:

    标签: python numpy boolean


    【解决方案1】:

    enumerate:

    >>> test = [True, False, True, True]
    >>> [i for i, b in enumerate(test) if b]
    [0, 2, 3]
    >>> [i for i, b in enumerate(test) if not b]
    [1]
    

    【讨论】:

    • 您也可以使用itertools.groupby 一次性完成这两项操作,但是类型转换会变得有点混乱
    • 有点不清楚,但 OP 肯定是在使用numpy,所以这个绝对不应该使用
    【解决方案2】:

    使用np.where(~test) 代替np.where(test)

    【讨论】:

      【解决方案3】:

      使用显式np.array()

      import numpy as np
      test = [True, False, True, True]
      a = np.array(test)
      test1 = np.where(a==False)[0]    #np.where(test)[0]
      print(test1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-21
        • 2018-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-05
        相关资源
        最近更新 更多