Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get unique values with respective occurrence count from a list in Python?

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.

like image 291
Samantha Green Avatar asked Mar 06 '10 15:03

Samantha Green


People also ask

Which syntax will you use to count number of unique values that occur in dataset or in a column?

value_counts(). This method returns the count of all unique values in the specified column.

How do you count occurrences of an item in a list?

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.


1 Answers

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)]

like image 64
mmmmmm Avatar answered Sep 22 '22 07:09

mmmmmm