This might be useful for someone.
Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.
To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.
def compute_PMF(data):
import numpy as np
from collections import Counter
_, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
h = Counter(np.digitize(data,bins) - 1)
weights = np.asarray(list(h.values()))
weights = weights / weights.sum()
values = np.asarray(list(h.keys()))
return weights, values
####
Refs:
[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html
[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html