How to Create Frequency Tables in Python?


A frequency table is a table that shows the frequency of each value or category in a dataset. In Python, we can create frequency tables using various libraries and functions. Here are some methods to create frequency tables in Python:

Method 1: Using the collections module

The collections module in Python provides a Counter class that can be used to create frequency tables. The Counter class takes an iterable as input and returns a dictionary with the frequency of each element in the iterable.

from collections import Counter

data = [1, 2, 3, 1, 2, 1, 3, 4, 5, 4, 3, 2, 1]

freq_table = Counter(data)

print(freq_table)

Output:

Counter({1: 4, 2: 3, 3: 3, 4: 2, 5: 1})

Method 2: Using the pandas library

The pandas library in Python provides a value_counts() function that can be used to create frequency tables. The value_counts() function takes a pandas Series as input and returns a pandas Series with the frequency of each unique value in the input Series.

import pandas as pd

data = [1, 2, 3, 1, 2, 1, 3, 4, 5, 4, 3, 2, 1]

freq_table = pd.Series(data).value_counts()

print(freq_table)

Output:

1    4
2    3
3    3
4    2
5    1
dtype: int64

Method 3: Using the numpy library

The numpy library in Python provides a unique() function that can be used to create frequency tables. The unique() function takes an array as input and returns a tuple with two arrays - the unique values in the input array and the frequency of each unique value.

import numpy as np

data = [1, 2, 3, 1, 2, 1, 3, 4, 5, 4, 3, 2, 1]

unique, counts = np.unique(data, return_counts=True)

freq_table = dict(zip(unique, counts))

print(freq_table)

Output:

{1: 4, 2: 3, 3: 3, 4: 2, 5: 1}

All of these methods can be used to create frequency tables in Python. The choice of method depends on the specific requirements of the task at hand.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.