number of element in array/matrix
tgrav at mac.com
Fri Jan 11 22:35:55 CET 2008
On Jan 11, 2008, at 11:09 AM, m.s.mould at durham.ac.uk wrote:
> I have what I suspect to be a fairly simple problem while using
> python Numeric.
> I am attempting to count the number of times that an element 'b'
> occurs in
> numeric array 'a'. I tried unsuccessfully to find a more efficient
> function to
> do this for me such as that offered when using a list, but couldn't
> seem to find
> anything for Numeric arrays. However, I suspect that my loop is not
> the most
> efficient way to achieve this.
> def countel(a, b): #counts the number of times value 'b' is found
> in array 'a'
> while (i<len(a)):
> while (j<len(a)):
> if (a[i][j]==b):
> return count
> Any help or advice would be greatly appreciated,
something like this?
>>> import numpy as n
>>> a = n.matrix([[1,2,3,4,1],[2,3,4,1,2],[3,4,1,2,3]],"float")
matrix([[ 1., 2., 3., 4., 1.],
[ 2., 3., 4., 1., 2.],
[ 3., 4., 1., 2., 3.]])
>>> k = n.where(a==1,1,0)
matrix([[1, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0]])
More information about the Python-list