scipy.stats.nbinom
uses a different n, p parameterisation than the one given. See the definition here https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.nbinom.html
You can use the following code to fit the parameters used by nbinom
to your sample:
# Estimate parameters
mu = np.mean(sample) # Mean
sigma_sqr = np.var(sample) # Variance
# Convert mean and variance to n, p parameterisation
n = mu**2 / (sigma_sqr - mu)
p = mu / sigma_sqr
If you want to test that the estimates actually work, compare them to true parameter values from simulated data:
# Generate sample data
n = 1000
p = 0.009
sample = nbinom.rvs(n=n, p=p, size=10000)
# Estimate parameters
mu = np.mean(sample) # Mean
sigma_sqr = np.var(sample) # Variance
# Convert mean and variance to n, p parameterisation
n_est = mu**2 / (sigma_sqr - mu)
p_est = mu / sigma_sqr
# Print results
print("""
{:<3} {:<3}
True parameters: {:<3} {:<3}
Estimates : {:<3} {:<3}""".format('n', 'p', n, p,
np.round(n_est, 0), np.round(p_est, 4)))
```