I have a list which has repeating items and I want a list of the unique items with their frequency.
For example, I have ['a', 'a', 'b', 'b', 'b']
, and I want [('a', 2), ('b', 3)]
.
Looking for a simple way to do this without looping twice.
value_counts(). This method returns the count of all unique values in the specified column.
Using the count() Function The "standard" way (no external libraries) to get the count of word occurrences in a list is by using the list object's count() function. The count() method is a built-in function that takes an element as its only argument and returns the number of times that element appears in the list.
With Python 2.7+, you can use collections.Counter
.
Otherwise, see this counter receipe.
Under Python 2.7+:
from collections import Counter input = ['a', 'a', 'b', 'b', 'b'] c = Counter( input ) print( c.items() )
Output is:
[('a', 2), ('b', 3)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With