Counter in Python | Python Collection for Counting Elements

Counter in Python is one of the most widely used collection in tasks especially data analysis. It keeps the count of the elements. Simply speaking, Counter in Python store the occurrences (frequency) of elements in collection. Let’s say we have list of countries, from where users access skilllx.com website. We might be interested in country, from where we have most of the users. We can use Counter in Python in this case.

from collections import Counter
countries_names = ["USA", "USA", "PAKISTAN", "PAKISTAN", "INDIA", "INDIA", "USA", "GERMANY", "CHINA"]
country_users =  Counter(countries_names)
print(country_users)
Counter({'USA': 3, 'PAKISTAN': 2, 'INDIA': 2, 'GERMANY': 1, 'CHINA': 1})

Why we use Python Counter?

  • Counter stores count of elements – hence no need to find the occurrences of each element using loop. This makes code efficient and simple.
  • Counter save elements in an unordered collection, just like hashtable objects. This help us to access data efficiently
  • We can apply Arithmetic operations like addition, subtraction, intersection, and union

Important Methods of Counter Object

elements()

This method returns all the elements with count greater than ZERO.

Elements with 0 or -1 count will not be returned.

from collections import Counter
counter =  Counter({'zero': 0, 'minus one': -1, 'one': 1, 'five':5})
for i in counter.elements():
    print(i)
one
five
five
five
five
five

Most Common Elements

This method returns the most common “N” elements from Counter list. “N” means how many elements you want, by default it returns all elements. Let say we have a list of messages where people discuss countries. Find the most discussed top 2 countries, for this we can use most_common() method.

from collections import Counter
countries_names = ["USA", "USA", "PAKISTAN", "PAKISTAN", "INDIA", "INDIA", "USA", "GERMANY", "CHINA"]
country_users =  Counter(countries_names)
print(country_users.most_common(2))
[('USA', 3), ('PAKISTAN', 2)]

Subtract Counters

This method is used to deduct the elements from another Counter. It will subtract second counter value (only count) from first counter.

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)
Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

How to Update Elements from another Counter?

We can use update() method to update the elements from another Counter. This method takes values from second Counter and add it to first counter.

from collections import Counter
counter1 =  Counter({'x': 5, 'y': 12, 'z': -2, 'x1':0})
counter2 = Counter({'x': 2, 'y':5})
counter1.update(counter2)
print(counter1)
Counter({'y': 17, 'x': 7, 'x1': 0, 'z': -2})

Any single values, can be simply update by assigning new value.

from collections import Counter
tokens = {"Engish":2, "Math":1, "Artificial Intelligence":3}
counter = Counter(tokens)
counter["Math"] = 10000
print(counter)
Counter({'Math': 10000, 'Artificial Intelligence': 3, 'Engish': 2})

Accessing Counter Values

We can access Counter values same as Python dictionary. We will use key to get count of that key.

from collections import Counter
counter = Counter("skilllx.com")
print(counter)
Counter({'l': 3, 's': 1, 'k': 1, 'i': 1, 'x': 1, '.': 1, 'c': 1, 'o': 1, 'm': 1})

Now we want to know the occurrence of character “l” in skilllx.com word.

print(counter["l"])
# 3

How to Initialize a Counter in Python?

You can easily initialize counter using following data structures:-

  • String
  • List or Similar containers such as Python Tuple
  • Python Dictionary
  • Keyword Arguments

Create Counter from String

We can create counter from string values. String values are basically list of characters. It will return dictionary, where keys will be the elements and values are the count of elements.

from collections import Counter
counter = Counter("skilllx.com")
print(counter)
Counter({'l': 3, 's': 1, 'k': 1, 'i': 1, 'x': 1, '.': 1, 'c': 1, 'o': 1, 'm': 1})

Do you know Tuple in Python?

Explain working of List in Python?

Counter from List

Similarly, we can make counter from list and similar data structures.

from collections import Counter
blood_groups = ["A+", "A-", "B+", "B+", "O-", "B+"]
counter = Counter(blood_groups)
print(counter)
Counter({'B+': 3, 'A+': 1, 'A-': 1, 'O-': 1})

What is Python dictionary and its application?

Dictionary to Counter

You cab pass dict as argument to counter, it will return counter object.

from collections import Counter
tokens = {"Engish":2, "Math":1, "Artificial Intelligence":3}
counter = Counter(tokens)
print(counter)

Keyword Arguments

The easiest way to initialize counter is using keyword arguments i-e like function calling.

from collections import Counter
counter =  Counter(a=10, b=5, c=3)
print(counter)
Counter({'a': 10, 'b': 5, 'c': 3})

You can clear complete counter object using clear() and delete one of the key using del operator

from collections import Counter
counter =  Counter(a=10, b=5, c=3)
counter.clear()
print(counter)
# Output
# Counter()
from collections import Counter
counter =  Counter(a=10, b=5, c=3)
del counter['a']
print(counter)
Counter({'b': 5, 'c': 3})

Python Counter Arithmetic Operations

In counter you can apply following arithmetic operators:

  • Addition (+): This operator add the values just like update() method. The difference is, addition operator does not shows the values which are less than ZERO
from collections import Counter
counter1 =  Counter(a=10, b=5, c=3)
counter2 = Counter({'a':2, 'b':9, "c":-4})
print(counter1 + counter2)
Counter({'b': 14, 'a': 12})
  • Negative (-): It is same as Addition, except it will subtract second counter (it will also ignore values less than ZERO)
from collections import Counter
counter1 =  Counter(a=10, b=10, c=3)
counter2 = Counter({'a':2, 'b':9, "c":-4})
print(counter1 - counter2)
Counter({'a': 8, 'c': 7, 'b': 1})
  • Minimum Values from Counters (&): This operator take minimum values from both counters. Let say value of “a” in counter1 is “10” and value of “a” in counter2 is “7”, it will bring “a=7”.
from collections import Counter
counter1 =  Counter(a=10, b=10)
counter2 = Counter({'a':2, 'b':9})
print(counter1 & counter2)
Counter({'b': 9, 'a': 2})
  • Maximum Values from Counters (|): This operator will take maximum values from both counters. Let say value of “a” in counter1 is “10” and value of “a” in counter2 is “7”, it will bring “a=10”.
from collections import Counter
counter1 =  Counter(a=10, b=5)
counter2 = Counter({'a':2, 'b':9})
print(counter1 | counter2)
Counter({'a': 10, 'b': 9})
30950cookie-checkCounter in Python | Python Collection for Counting Elements

Leave a Reply