Boolean array with no all True values in one row

爷,独闯天下 提交于 2020-01-02 12:40:10

问题


I have 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]]

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

Ugly solution is:

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?


回答1:


You could do:

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)

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

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)

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

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

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




回答2:


Here's a fair one (all legal triplets equally likely):

N = 10
bits = np.random.randint(7, size=(N,))
mask = (bits[:, None] & 2**np.arange(3)).astype(bool)


来源:https://stackoverflow.com/questions/42092335/boolean-array-with-no-all-true-values-in-one-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!