Skip to main content

Section 2.1 Frequency Tables

One way to describe a variable is a frequency table, which contains the values of the variable and their frequencies β€” that is, the number of times each value appears. This description is called the distribution of the variable.
To represent distributions, we’ll use a library called empiricaldist. In this context, "empirical" means that the distributions are based on data rather than mathematical models. empiricaldist provides a class called FreqTab that we can use to compute and plot frequency tables. We can import it like this.
Listing 2.1.1. Python Code
from empiricaldist import FreqTab
To show how it works, we’ll start with a small list of values.
Listing 2.1.2. Python Code
t = [1.0, 2.0, 2.0, 3.0, 5.0]
FreqTab provides a method called from_seq that takes a sequence and makes a FreqTab object.
Listing 2.1.3. Python Code
$ ftab = FreqTab.from_seq(t)
ftab
1.0    1
2.0    2
3.0    1
5.0    1
Name: , dtype: int64
A FreqTab object is a kind of Pandas Series that contains values and their frequencies. In this example, the value 1.0 has frequency 1, the value 2.0 has frequency 2, etc.
FreqTab provides a method called bar that plots the frequency table as a bar chart.
Listing 2.1.4. Python Code
ftab.bar()
decorate(xlabel="Value", ylabel="Frequency")
Figure 2.1.5.
Because a FreqTab is a Pandas Series, we can use the bracket operator to look up a value and get its frequency.
Listing 2.1.6. Python Code
$ ftab[2.0]
np.int64(2)
But unlike a Pandas Series, we can also call a FreqTab object like a function to look up a value.
Listing 2.1.7. Python Code
$ ftab(2.0)
np.int64(2)
If we look up a value that does not appear in the FreqTab, the function syntax returns 0.
Listing 2.1.8. Python Code
$ ftab(4.0)
0
A FreqTab object has an attribute called qs that returns an array of values β€” qs stands for quantities, although technically not all values are quantities.
Listing 2.1.9. Python Code
$ ftab.qs
array([1., 2., 3., 5.])
FreqTab also has an attribute called fs that returns an array of frequencies.
Listing 2.1.10. Python Code
$ ftab.fs
array([1, 2, 1, 1])
FreqTab provides an items method we can use to loop through quantity-frequency pairs:
Listing 2.1.11. Python Code
$ for x, freq in ftab.items():
    print(x, freq)
1.0 1
2.0 2
3.0 1
5.0 1
We’ll see more FreqTab methods as we go along.