在一行中没有所有True值的布尔数组 [英] Boolean array with no all True values in one row

查看:81
本文介绍了在一行中没有所有True值的布尔数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有numpy array:

np.random.seed(100)
mask = np.random.choice([True, False], size=(10,3))
print (mask)
[[ True  True False]
 [False False False]
 [ True  True  True] <- problem - all values True
 [ True  True False]
 [ True  True  True] <- problem - all values True
 [ True False  True]
 [ True False  True]
 [False  True  True]
 [ True False False]
 [False  True  True]]

每行都不需要所有值True-因此这里只能是012 True,因为3 'columns'.

Need in each row no all values True - so here can be only 0, 1 or 2 True because 3 'columns'.

丑陋的解决方法是:

mask[:, -1] = False
print (mask)
[[ True  True False]
 [False False False]
 [ True  True False]
 [ True  True False]
 [ True  True False]
 [ True False False]
 [ True False False]
 [False  True False]
 [ True False False]
 [False  True False]]

什么是更好,更通用的解决方案?

What is better and more generic solution?

推荐答案

您可以这样做:

In [109]:
mask[mask.all(axis=1),-1] = False
mask

Out[109]:
array([[ True,  True, False],
       [False, False, False],
       [ True,  True, False],
       [ True,  True, False],
       [ True,  True, False],
       [ True, False,  True],
       [ True, False,  True],
       [False,  True,  True],
       [ True, False, False],
       [False,  True,  True]], dtype=bool)

因此,只需使用all逐行进行测试,并在这种情况下仅将第三个列设置为False

So just test row-wise using all and only set the 3rd col to False on this condition

感谢@Divakar,您可以输入更少的内容:

Thanks to @Divakar, you could type less:

In [110]:
mask[mask.all(1),2] = 0
mask

Out[110]:
array([[ True,  True, False],
       [False, False, False],
       [ True,  True, False],
       [ True,  True, False],
       [ True,  True, False],
       [ True, False,  True],
       [ True, False,  True],
       [False,  True,  True],
       [ True, False, False],
       [False,  True,  True]], dtype=bool)

因此在这里设置了位置arg axis,并且将0强制转换为布尔值False,否则是相同的

So here the position arg axis is being set and 0 is being cast to boolean False otherwise is same

一些解释,首先使用allaxis=1来逐行测试是否都是True.

Some explanation, first use all with axis=1 to test row-wise if all are True.

然后,我们使用该掩码遮罩方括号中的行,第二个arg -1选择最后一列,最后分配新的所需值

Then we use that mask to mask the rows in the square brackets, the second arg -1 selects the last column and finally we assign the new desired value

这篇关于在一行中没有所有True值的布尔数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆