TExcelTAD
Home › NumPy › Data Distribution

Random Data Distribution

A data distribution describes all the possible values of something and how often each one occurs. The outcomes of a fair die are spread evenly over 1–6; adult heights cluster around an average with fewer very short or very tall people. In statistics and data science, distributions are how we describe data and how we generate realistic fake data.

A random distribution is a set of random numbers that follow a given probability density function (PDF): a rule saying how likely each value is.

Choosing values with given probabilities

rng.choice accepts a p argument: a list of probabilities, one per option, that must add up to 1. Here a weighted die lands on 6 half of the time:

python · try it yourself
import numpy as np

rng = np.random.default_rng(12)
faces = [1, 2, 3, 4, 5, 6]
p = [0.1, 0.1, 0.1, 0.1, 0.1, 0.5]

rolls = rng.choice(faces, p=p, size=20)
print(rolls)
[3 6 2 2 4 3 6 2 6 6 1 6 2 3 5 5 5 6 3 2]

Even in only 20 rolls, the 6s stand out. With probability 0, a value can never appear; with probability 1, it is the only value that appears.

Measuring a distribution: counting outcomes

To see the distribution of a sample, count how often each value occurs. np.unique(..., return_counts=True) does that in one call. With many samples, the observed frequencies get close to the probabilities we asked for:

python · try it yourself
import numpy as np

rng = np.random.default_rng(12)
faces = [1, 2, 3, 4, 5, 6]
p = [0.1, 0.1, 0.1, 0.1, 0.1, 0.5]

rolls = rng.choice(faces, p=p, size=10_000)
values, counts = np.unique(rolls, return_counts=True)
for v, c in zip(values, counts):
    print(f"face {v}: {c:5d} times  ({c / len(rolls):.3f})")
face 1:   996 times  (0.100)
face 2:   969 times  (0.097)
face 3:  1016 times  (0.102)
face 4:   994 times  (0.099)
face 5:  1009 times  (0.101)
face 6:  5016 times  (0.502)

This is the law of large numbers at work: the more samples you draw, the closer the observed frequencies come to the true probabilities.

Shaped samples

size can be a shape, just as for other generator methods. Below we simulate a weather model for 3 cities over 7 days, where each day is sunny, cloudy or rainy:

python · try it yourself
import numpy as np

rng = np.random.default_rng(5)
weather = rng.choice(["sun", "cloud", "rain"], p=[0.5, 0.3, 0.2], size=(3, 7))
print(weather)
print("rainy days per city:", (weather == "rain").sum(axis=1))
[['rain' 'rain' 'cloud' 'sun' 'sun' 'sun' 'sun']
 ['sun' 'sun' 'rain' 'cloud' 'sun' 'sun' 'rain']
 ['rain' 'rain' 'sun' 'sun' 'cloud' 'sun' 'cloud']]
rainy days per city: [2 2 2]

Seeing a distribution with a plot

Numbers in a table are hard to compare; a bar chart of the counts shows the distribution at a glance:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(12)
faces = np.arange(1, 7)
p = [0.1, 0.1, 0.1, 0.1, 0.1, 0.5]
rolls = rng.choice(faces, p=p, size=1000)
values, counts = np.unique(rolls, return_counts=True)

plt.figure(figsize=(6, 3.5))
plt.bar(values, counts / len(rolls), color="#4dabcf", label="observed")
plt.plot(faces, p, "o--", color="black", label="probability")
plt.xlabel("die face")
plt.ylabel("frequency")
plt.title("1000 rolls of a weighted die")
plt.legend()
plt.tight_layout()
plt.show()
print("Plotted observed frequencies of", len(rolls), "rolls")
Plotted observed frequencies of 1000 rolls

The bars (observed) sit close to the dots (the probabilities we specified). In the next lessons, every named distribution (normal, binomial, Poisson, …) is just a different rule for these probabilities, and NumPy has a generator method for each of them.

Kind Values Examples
Discrete separate values you can count die faces, number of emails per hour
Continuous any value in a range height, waiting time, temperature

Test yourself

What must be true about the p list passed to rng.choice?

  1. It must be sorted
  2. Its values must add up to 1
  3. It must contain integers
  4. It must have length 6

What happens to observed frequencies as you draw more samples?

  1. They drift away from the probabilities
  2. They approach the true probabilities
  3. They become all equal
  4. Nothing changes

Which of these is a continuous distribution?

  1. Number of goals in a match
  2. Faces of a die
  3. Time until the next bus arrives
  4. Number of heads in 10 coin flips