To count the occurences of a value in a numpy array. This will work:
The logic is that the boolean statement produces a array where all occurences of the requested values are 1 and all others are zero. So summing these gives the number of occurencies. This works for arrays of any shape or dtype.
There are two methods I use to count occurences of all unique values in numpy. Unique and bincount. Unique automatically flattens multidimensional arrays, while bincount only works with 1d arrays only containing positive integers.
If your data are numpy arrays it is generally much faster to use numpy methods then to convert your data to generic methods.
Counting all occurence of all items in an iterable: collections.Counter
The collections.Counter can be used for any iterable and counts every occurrence for every element.
Note: One exception is if a dict or another collections.Mapping-like class is given, then it will not count them, rather it creates a Counter with these values:
Counting the occurrences of a substring in a string: str.count()
This works even for substrings longer than one character:
which would not be possible with collections.Counter which only counts single characters:
Counting the occurrences of one item in a sequence: list.count() and tuple.count()
Getting the most common value(-s): collections.Counter.most_common()
Counting the keys of a Mapping isn't possible with collections.Counter but we can count the values:
The most common elements are avaiable by the most_common-method:
This modified text is an extract of the original Stack Overflow Documentation created by following contributors and released under CC BY-SA 3.0