[Numpy-discussion] Numpy Help

Martin Ling martin-numpy at earth.li
Fri Jul 29 10:24:35 EDT 2011


On Fri, Jul 29, 2011 at 02:55:15PM +0100, DIPO ELEGBEDE wrote:
> 
>    I have a 4 by 4 matrix filled with 0s, 1s and 2s.
>    I want to loop through the whole matrix to get the fields with 1s and 2s
>    only and then count how many ones and how many twos.

Try this:

>>> m = matrix('1,2,0,2;2,2,1,0;0,2,0,2;1,1,0,2')

>>> m
matrix([[1, 2, 0, 2],
        [2, 2, 1, 0],
        [0, 2, 0, 2],
        [1, 1, 0, 2]])

>>> sum(m == 1)
4
>>> sum(m == 2)
7

This works because 'm == 1' evaluates to a boolean matrix whose elements
are true where that element of m is equal to 1:

>>> m == 1
matrix([[ True, False, False, False],
        [False, False,  True, False],
        [False, False, False, False],
        [ True,  True, False, False]], dtype=bool)

Calling sum() on this matrix adds up the number of true elements.

I suggest you read the NumPy tutorial:
http://www.scipy.org/Tentative_NumPy_Tutorial

This sort of thing is covered under 'Indexing with Boolean Arrays':
http://www.scipy.org/Tentative_NumPy_Tutorial#head-d55e594d46b4f347c20efe1b4c65c92779f06268



Martin



More information about the NumPy-Discussion mailing list