检查数组中是否存在布尔的组合



我有一个多维字符串数组,看起来类似于下面的。第一列是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。类似于以下内容,尽管以下内容不起作用:

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个值都为真的行,因此打印出在比较中没有所有3个变量为真的ID。

试试这个代码。

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

此任务可以使用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))

最新更新