1
$\begingroup$
list = {{0, 1, 2}, {3, 0, 4}, {4,5,6}};

How do I calculate the mean of the rows but ignoring the entries that have a 0? The answers should be 1.5, 3.5, 5.0.

$\endgroup$
7
  • 1
    $\begingroup$ It's simple, I think: Map[Mean[#]&, DeleteCases[list,0]] $\endgroup$ Mar 31, 2017 at 20:33
  • 1
    $\begingroup$ @RiccardoCazzin You didn't remove the zeros. Also, you can replace Mean[#]& with simply Mean. $\endgroup$
    – jjc385
    Mar 31, 2017 at 20:47
  • 1
    $\begingroup$ Try something like N@*Mean@*DeleteCases[0] /@ list. $\endgroup$
    – jjc385
    Mar 31, 2017 at 20:48
  • 1
    $\begingroup$ Mean /@ DeleteCases[list, 0, Infinity] $\endgroup$
    – corey979
    Mar 31, 2017 at 20:49
  • 1
    $\begingroup$ @jjc385 you're right: it's Map[Mean, DeleteCases[list, 0, 2]] $\endgroup$ Mar 31, 2017 at 20:50

3 Answers 3

2
$\begingroup$

First delete the zeros with DeleteCases (on all levels), the Map (/@) the Mean on all rows:

Mean /@ DeleteCases[list, 0, Infinity]

{3/2, 7/2, 5}

You can add N if you want decimal output:

N@%

{1.5, 3.5, 5.}

$\endgroup$
2
  • 1
    $\begingroup$ Why Infinity rather than {2}? Presumably the latter is more efficient. +1 $\endgroup$
    – jjc385
    Mar 31, 2017 at 20:58
  • 2
    $\begingroup$ @jjc385 Because it's more general. If you want to make it a function and then use on something with more levels, you'll need to adjust. If you have a specific issue just go with {2}, but I'd go with Infinity to not worry in the future. $\endgroup$
    – corey979
    Mar 31, 2017 at 21:00
4
$\begingroup$

Replace 0's with Nothing to remove them from the list

Mean /@ (list /. 0 -> Nothing)
$\endgroup$
2
  • 1
    $\begingroup$ @TomMozdzen add a space between /. and 0 $\endgroup$
    – Ali Hashmi
    Mar 31, 2017 at 22:02
  • $\begingroup$ My bad - had a white space issue - yes works great too! $\endgroup$ Mar 31, 2017 at 22:04
4
$\begingroup$

If your lists are large, this s/b faster (if speed matters):

Total[#]/Total[Unitize@#] &@Transpose@list
$\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.