【问题标题】:Check to see if a combination of bools exists in an array?检查数组中是否存在布尔组合?
【发布时间】:2020-07-20 19:56:24
【问题描述】:

我有一个类似于以下内容的多维字符串数组。第一列是ID,第2-4列是三个不同的变量:

              #ID    Var1    Var2   Var3
comparison = [['1' 'False' 'False' 'True']
              ['2' 'False' 'True' 'False']
              ['3' 'False' 'True' 'False']
              ...
              ['98' 'False' 'True' 'False']
              ['99' 'False' 'True' 'False']
              ['100' 'False' 'True' 'False']]

我有一个循环打印出所有三个变量都为真的地方,这很好用:

true_vars = np.array([])

for idx in comparison:
    if ((idx[1] == 'True') and (idx[2] == 'True') and (idx[3] == 'True')):
        true_vars = np.append(true_vars, idx)

但是我想编写另一个循环来检查在 100 行的总数组中是否没有所有三个变量都为真的 ID。尽管以下内容不起作用,但类似于以下内容:

true_vars = np.array([])

for idx in comparison:
    if ((idx[1] == 'True') and (idx[2] == 'True') and (idx[3] == 'True')):
        true_vars = np.append(true_vars, idx)
    elif not exist ((idx[1] == 'True') and (idx[2] == 'True') and (idx[3] == 'True')):
        print('there are no true ID's in comparison') 

所以理想的情况是它遍历我的比较数组中的所有 100 行,没有找到所有 3 个值都为真的任何行,因此打印出相比之下,没有 ID 的所有 3 个变量都为真。

【问题讨论】:

  • 我不明白问题出在哪里。不能简单检查一下true_vars最后是否为空吗?

标签: python arrays numpy loops


【解决方案1】:

试试这个代码。

import numpy as np

comparison = [['1', 'False', 'True', 'True'],
          ['2', 'False', 'True', 'False'],
          ['3', 'True', 'True', 'True'],
          ['100', 'False', 'True', 'False']]

true_vars = np.array([])

for idx in comparison:
  if ((idx[1] == 'True') and (idx[2] == 'True') and (idx[3] == 'True')):
    true_vars = np.append(true_vars, idx)
  if idx[0] == '100' and len(true_vars) == 0:
    print('there are no true ID\'s in comparison') 
    break

【讨论】:

    【解决方案2】:

    使用np.ndarray.all 方法可以在不使用for 循环的情况下完成此任务:

    import numpy as np
    
    comparison = np.array([['1', 'False', 'False', 'True'],
                           ['2', 'False', 'True', 'False'],
                           ['3', 'False', 'True', 'False'],
                           ...
                           ['98', 'False', 'True', 'False'],
                           ['99', 'False', 'True', 'False'],
                           ['100', 'False', 'True' ,'False']])
    
    # Since you values are string we compare them with 'True' to get booleans:
    (comparison[:,1:] == 'True').all(axis=1)
    array([False, False, False,..., False, False, False])
    
    

    现在,如果您想检查其中任何一项是否属实,您可以使用np.any

    np.any((comparison[:,1:] == 'True').all(axis=1))
    

    【讨论】:

      猜你喜欢
      • 2013-09-18
      • 1970-01-01
      • 1970-01-01
      • 2021-03-12
      • 1970-01-01
      • 2011-06-20
      • 1970-01-01
      • 2023-03-26
      相关资源
      最近更新 更多