Skip to main content
HomeAbout PythonLearn Python

Python Count Tutorial

Learn how to use the counter tool with an interactive example.
Sep 2020  · 3 min read

When working with data, you are often going to need to count items, create dictionaries values before you know keys to store them in, or maintain order in a dictionary.

Counter is a powerful tool for counting, validating, and learning more about the elements within a dataset that is found in the collections module. You pass an iterable (list, set, tuple) or a dictionary to the Counter. You can also use the Counter object similarly to a dictionary with key/value assignment, for example, counter[key] = value.

A common usage for Counter is checking data for consistency prior to using it.

Counter Module

The counter module is based on dictionary; you can use all of the normal dictionary features. In this example, we have the list named nyc_eatery_types that contains one column of data called type from a table about eateries in NYC parks. We create a new counter based on that list and print it.

from collections import Counter
nyc_eatery_count_by_types = Counter(nyc_eatery_types)
print(nyc_eatery_count_by_types)
Counter({'Mobile Food Truck': 114, 'Food Cart': 74, 'Snack Bar': 24,
'Specialty Cart': 18, 'Restaurant': 15, 'Fruit & Vegetable Cart': 4})

You can see each type from the list and the number of times it was found in the list. We can also see how many restaurants are in the counter by using Restaurant as the index and printing it.

print(nyc_eatery_count_by_types['Restaurant'])
15

Using Counter to Find the Most Common

Counters also provide a wonderful way to find the most common values they contain. The most_common() method on a Counter returns a list of tuples containing the items and their count in descending order.

Let's print the top 3 eatery types in the NYC park system with the most_common() method and pass it 3 as the number items to return.

print(nyc_eatery_count_by_types.most_common(3))
[('Mobile Food Truck': 114), ('Food Cart': 74), ('Snack Bar': 24)]

most_common() is excellent for frequency analytics and finding out how often an item occurs.

Interactive Example

In the following example, you will:

  • Use the data from the Chicago Transit Authority on ridership.
  • Import the Counter object from collections.
  • Print the first ten items from the stations list.
  • Create a Counter of the stations list called station_count.
  • Print the station_count.
# Import the Counter object
from collections import Counter

# Print the first ten items from the stations list
print(stations[:10])

# Create a Counter of the stations list: station_count
station_count = Counter(stations)

# Print the station_count
print(station_count)

When we run the above code, it produces the following result:

['stationname', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park', 'Austin-Forest Park']
Counter({'California-Cermak': 700, 'Damen-Cermak': 700, 'Ashland-Orange': 700, 'Argyle': 700, 'Halsted-Orange': 700, 'Laramie': 700, 'Diversey': 700, '79th': 700, 'Clinton-Lake': 700, 'Monroe/Dearborn': 700, 'Wellington': 700, 'Merchandise Mart': 700, 'Cicero-Cermak': 700, 'Kedzie-Lake': 700, 'Southport': 700, 'Washington/Wells': 700, 'Clark/Division': 700, 'stationname': 1})

Try it for yourself.

To learn more about the collections module for counting, please see this video from our course Data Types for Data Science in Python.

This content is taken from DataCamp’s Data Types for Data Science in Python course by Jason Myers.

Check out our Python Data Structures Tutorial.

Topics

Python Courses

Course

Introduction to Python

4 hr
5.4M
Master the basics of data analysis with Python in just four hours. This online course will introduce the Python interface and explore popular packages.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

Mastering the Pandas .explode() Method: A Comprehensive Guide

Learn all you need to know about the pandas .explode() method, covering single and multiple columns, handling nested data, and common pitfalls with practical Python code examples.
Adel Nehme's photo

Adel Nehme

5 min

Python NaN: 4 Ways to Check for Missing Values in Python

Explore 4 ways to detect NaN values in Python, using NumPy and Pandas. Learn key differences between NaN and None to clean and analyze data efficiently.
Adel Nehme's photo

Adel Nehme

5 min

Seaborn Heatmaps: A Guide to Data Visualization

Learn how to create eye-catching Seaborn heatmaps
Joleen Bothma's photo

Joleen Bothma

9 min

Test-Driven Development in Python: A Beginner's Guide

Dive into test-driven development (TDD) with our comprehensive Python tutorial. Learn how to write robust tests before coding with practical examples.
Amina Edmunds's photo

Amina Edmunds

7 min

Exponents in Python: A Comprehensive Guide for Beginners

Master exponents in Python using various methods, from built-in functions to powerful libraries like NumPy, and leverage them in real-world scenarios to gain a deeper understanding.
Satyam Tripathi's photo

Satyam Tripathi

9 min

Python Linked Lists: Tutorial With Examples

Learn everything you need to know about linked lists: when to use them, their types, and implementation in Python.
Natassha Selvaraj's photo

Natassha Selvaraj

9 min

See MoreSee More