In python I'm used to doing something like np.mean([True, False, True......])
to compute the fraction of True
values in a list. Is there some equivalent in mathematica?
Using Cases
or Count
seems way too verbose.
Use Boole
to convert truth values to numbers.
Mean@Boole@{True, False, True}
(* 2/3 *)
list = {True, True, False, True, False, True, False, True, True, True}
Using Mean gives:
Mean[list]
Out: 1/10 (3 False + 7 True)
Then you can replace False and True with 0 and 1 respectively:
Mean[list] /. False -> 0 /. True -> 1
Out: 7/10
Using ProportionsBy
by Richard Hennigan (Wolfram Research)
ProportionsBy = ResourceFunction["ProportionsBy"];
ProportionsBy[{True, False, True}, TrueQ]
<|True -> 2/3, False -> 1/3|>
%[True]
2/3
SeedRandom[1];
list = RandomChoice[{True, False}, 11]
{False, False, True, False, True, True, True, False, True, False,
True}
Count[#, True]/Length@# &@list
6/11