Python 3.13+Numbers & mathfunction
statistics.kde_random
statistics
Return a random-number generator drawing from a kernel density estimate (3.13+).
Syntax
statistics.kde_random(data, h, kernel='normal')
Unlike random.choice over the same sample, this smooths: it emits values between the observations and beyond their range, not just the numbers you fed in. With the normal kernel that easily yields a negative draw for a quantity like an age or a duration, so validate the output or pick a kernel with finite support when the data is bounded. Passing seed makes the stream reproducible; without it every run differs.
Examples
import statistics
print(not hasattr(statistics, 'kde_random') or callable(statistics.kde_random)) # → True
rand = statistics.kde_random([0, 10], h=2, kernel='uniform', seed=1) # прямоугольное ядро, seed делает выборку воспроизводимой
print(type(rand())) # → <class 'float'>
print(all(-2 <= rand() <= 12 for _ in range(100))) # → True
print(statistics.kde_random([1, 2, 3], h=0)) # → StatisticsError
See also
Open in the full glossarydocs.python.orgReport an inaccuracy