aldorado
aldorado

Reputation: 4864

How to count the frequency of an element in an ndarray

I have a numpy ndarray of strings and want to find out how often a certain word appears in the array. I found out this solution:

letters = numpy.array([["a","b"],["c","a"]])
print (numpy.count_nonzero(letters=="a"))

-->2

I'm just wondering if i solved this problem unnecessarily complicated or if this is the simplest solution, because for lists there is a simple .count().

Upvotes: 4

Views: 11111

Answers (1)

falsetru
falsetru

Reputation: 369444

You can also use sum:

>>> letters = numpy.array([["a","b"],["c","a"]])
>>> (letters == 'a').sum()
2
>>> numpy.sum(letters == 'a')
2

Upvotes: 5

Related Questions