问题
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