5
$\begingroup$

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.

$\endgroup$

4 Answers 4

13
$\begingroup$

Use Boole to convert truth values to numbers.

Mean@Boole@{True, False, True}
(* 2/3 *)
$\endgroup$
3
$\begingroup$
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
$\endgroup$
2
$\begingroup$

Using ProportionsBy by Richard Hennigan (Wolfram Research)

ProportionsBy = ResourceFunction["ProportionsBy"];

ProportionsBy[{True, False, True}, TrueQ]

<|True -> 2/3, False -> 1/3|>

%[True]

2/3

$\endgroup$
1
$\begingroup$
SeedRandom[1];
list = RandomChoice[{True, False}, 11]

{False, False, True, False, True, True, True, False, True, False,
True}

Count[#, True]/Length@# &@list

6/11

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.