# frequency (count) in Numpy Array

Hi experts!

For a list L the command L.count(z) shows the number of times that the element z is repeated in list L.

For example:

[I] L=[1,1,3,1,4,5,8]
[I] L.count(1)
[O] 3


How can i do that with a Numpy array?

Thanks a lot!

edit retag close merge delete

Sort by » oldest newest most voted

Of course you could always convert the array to a list:

sage: import numpy as np
sage: L = np.array([1,1,3,1,4,5,8])
sage: list(L).count(1)
3


but here is something more direct:

sage: (L == 1).sum()
3


or

sage: sum(L == 1)
3


Also, if you want to count occurrences of every element in the array, you can do:

sage: from collections import Counter
sage: Counter(L)
Counter({1: 3, 8: 1, 3: 1, 4: 1, 5: 1})


The command sum will also count how many elements in an array satisfy a property.

For example to see how many are odd:

sage: (L%2).sum()
5


or how many are between 3 and 5:

sage: ((3r <= L) & (L <= 5r)).sum()
3


(here 3r and 5r are a way to input raw Python integers, as the comparison with Sage integers would not work well -- I'm not sure why).

more

Thanks slelievre!!

Case closed

more