How to count element frequency in ndarray

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

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

-> 2

I'm just wondering if this problem has not been resolved too complex or if this is the easiest solution, because there is a simple .count () for lists.

+4
source share
1 answer

You can also use sum :

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

Source: https://habr.com/ru/post/1501498/


All Articles