# How to calculate the mean value of the rows of a matrix, ignoring any values equal to 0

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.

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

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.}

• Why Infinity rather than {2}? Presumably the latter is more efficient. +1 Mar 31, 2017 at 20:58
• @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. Mar 31, 2017 at 21:00

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

Mean /@ (list /. 0 -> Nothing)

• @TomMozdzen add a space between /. and 0 Mar 31, 2017 at 22:02
• My bad - had a white space issue - yes works great too! Mar 31, 2017 at 22:04

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

Total[#]/Total[Unitize@#] &@Transpose@list