Counter for Frequency
Concepts covered: Frequency Counting
Counting by hand means a dict plus, for every item, a membership check before the += 1. collections.Counter is a dict subclass built for tallies: pass it any iterable and it counts each item, and reading a key it never saw returns 0 instead of raising KeyError.
from collections import Counter
statuses = [200, 500, 200, 404, 200, 500, 301]
counts = Counter(statuses)
print(counts)
print(counts[200], counts[418])
print(418 in counts)
print(counts.most_common(2))Output:
Counter({200: 3, 500: 2, 404: 1, 301: 1})
3 0
False
[(200, 3), (500, 2)]The repr runs from most to least common, so 404 precedes 301 only because it was seen first. counts[418] returned 0 without storing 418, which is why 418 in counts stays False. And most_common(2) returns (item, count) pairs, highest count first, ties in first-seen order.
- Counting with a plain dict
- An if key not in counts check before every increment
- Reading an unseen key raises KeyError
- Top 2 needs sorted() with a key function, then a slice
- Merging 2 days of counts is a loop you write
- Counting with Counter
- Counter(statuses) counts the whole list in a single call
- Reading an unseen key returns 0
- Top 2 is counts.most_common(2)
- Merging 2 days is monday + tuesday
Combining counts with +, - and subtract()
Counters support arithmetic, which suits daily tallies that roll up into weekly ones. + adds counts key by key. - subtracts and then drops every key whose result is 0 or below, while the subtract() method changes the counter in place and keeps negatives. Before running this, decide which keys survive monday - tuesday.
from collections import Counter
monday = Counter({"login": 40, "search": 25, "checkout": 5})
tuesday = Counter({"login": 35, "search": 30, "refund": 2})
print((monday + tuesday).most_common(2))
print(monday - tuesday)
monday.subtract(tuesday)
print(monday)Output:
[('login', 75), ('search', 55)]
Counter({'login': 5, 'checkout': 5})
Counter({'login': 5, 'checkout': 5, 'refund': -2, 'search': -5})search fell from 25 to -5, so - dropped it and subtract() kept it. refund never appeared on Monday: - ignored it, while subtract() recorded -2. Reach for - when a negative count means nothing, such as units left in a warehouse bin, and for subtract() when falling below zero is the signal you want to see.
Feeding Counter the right items
A Counter counts whatever its iterable yields, and a string yields characters, so passing a raw log line tallies letters and spaces. Split the line to count words. update() adds another batch to an existing counter, which fits log lines arriving item by item.
from collections import Counter
lines = ["error timeout", "error disk", "warn timeout"]
print(Counter(lines[0]).most_common(2))
words = Counter()
for line in lines:
words.update(line.split())
print(words.most_common(2))
print(sum(words.values()))Output:
[('r', 3), ('e', 2)]
[('error', 2), ('timeout', 2)]
6Python 3.10 added Counter.total(). On 3.9, sum(words.values()) gives the same number, as the last line does.
Reads and writes behave differently on a Counter. A read of a missing key, counts['x'], answers 0 without storing anything. Any assignment stores. That includes += 1, which assigns 1 after fetching the 0. An assigned 0 stays stored as well. Once counts['x'] = 0 runs, 'x' in counts is True, and the key counts toward len(counts), which grows by 1. Unary plus, +counts, returns a new Counter with every zero and negative count removed, which tidies up after subtract().
What does this program print?
from collections import Counter
c = Counter(["a", "b", "a"])
if c["z"] == 0:
c["y"] += 1
print(len(c), c["y"])- 3 1: reading z stores nothing, while += 1 stores y with count 1
- 4 1: reading z stores it with count 0, and += 1 stores y
- 2 0: a missing key reads as 0, and writes to it are ignored
- KeyError, because y had no count before += 1 read it
About this lesson
This section is part of the Collections: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.