是否有任何函数或库可以帮助我绘制样本的概率质量函数,就像绘制样本的概率密度函数一样?
例如,使用pandas,绘制PDF就像调用:
一样简单sample.plot(kind="density")
如果没有简单的方法,我如何计算PMF,以便我可以使用matplotlib进行绘图?
答案 0 :(得分:9)
如果ts
是一个系列,您可以通过以下方式获得样本的PMF:
>>> pmf = ts.value_counts().sort_index() / len(ts)
并通过以下方式绘制:
>>> pmf.plot(kind='bar')
可以使用np.unique
>>> xs = np.random.randint(0, 10, 100)
>>> xs
array([5, 2, 2, 1, 2, 8, 6, 7, 5, 3, 2, 6, 4, 9, 7, 6, 4, 7, 6, 8, 7, 0, 6,
2, 9, 8, 7, 7, 2, 6, 2, 8, 0, 2, 5, 1, 3, 6, 7, 7, 2, 2, 0, 3, 8, 7,
4, 0, 5, 7, 5, 4, 4, 9, 5, 1, 6, 6, 0, 9, 4, 2, 0, 8, 7, 5, 1, 1, 2,
8, 3, 8, 9, 0, 0, 6, 8, 7, 2, 6, 7, 9, 7, 8, 8, 3, 3, 7, 8, 2, 2, 4,
4, 5, 3, 4, 1, 5, 5, 1])
>>> val, cnt = np.unique(xs, return_counts=True)
>>> pmf = cnt / len(xs)
>>> # values along with probability mass function
>>> np.column_stack((val, pmf))
array([[ 0. , 0.08],
[ 1. , 0.07],
[ 2. , 0.15],
[ 3. , 0.07],
[ 4. , 0.09],
[ 5. , 0.1 ],
[ 6. , 0.11],
[ 7. , 0.15],
[ 8. , 0.12],
[ 9. , 0.06]])
答案 1 :(得分:1)
给出df
的熊猫数据框,使用seaborn可以编写
import seaborn as sns
probabilities = df['SomeColumn'].value_counts(normalize=True)
sns.barplot(probabilities.index, probabilities.values)
答案 2 :(得分:0)
您可以使用np.histogram
使用density=true
计算PMF,前提是使用了单位宽度的区间(否则您将获得概率密度函数的值) bin很可能不是你需要的。)
>>> xs = np.array(
[5, 2, 2, 1, 2, 8, 6, 7, 5, 3, 2, 6, 4, 9, 7, 6, 4, 7, 6, 8, 7, 0, 6,
2, 9, 8, 7, 7, 2, 6, 2, 8, 0, 2, 5, 1, 3, 6, 7, 7, 2, 2, 0, 3, 8, 7,
4, 0, 5, 7, 5, 4, 4, 9, 5, 1, 6, 6, 0, 9, 4, 2, 0, 8, 7, 5, 1, 1, 2,
8, 3, 8, 9, 0, 0, 6, 8, 7, 2, 6, 7, 9, 7, 8, 8, 3, 3, 7, 8, 2, 2, 4,
4, 5, 3, 4, 1, 5, 5, 1])
>>> pmf, bins = np.histogram(xs, bins=range(0,11), density=True)
>>> np.column_stack((bins[:-1], pmf))
array([[ 0. , 0.08],
[ 1. , 0.07],
[ 2. , 0.15],
[ 3. , 0.07],
[ 4. , 0.09],
[ 5. , 0.1 ],
[ 6. , 0.11],
[ 7. , 0.15],
[ 8. , 0.12],
[ 9. , 0.06]])
答案 3 :(得分:0)
import matplotlib.pyplot as plt
import seaborn as sns
samp = [5, 2, 2, 1, 2, 8, 6, 7, 5, 3, 2, 6, 4, 9, 7, 6, 4, 7, 6, 8, 7, 0, 6,
2, 9, 8, 7, 7, 2, 6, 2, 8, 0, 2, 5, 1, 3, 6, 7, 7, 2, 2, 0, 3, 8, 7,
4, 0, 5, 7, 5, 4, 4, 9, 5, 1, 6, 6, 0, 9, 4, 2, 0, 8, 7, 5, 1, 1, 2,
8, 3, 8, 9, 0, 0, 6, 8, 7, 2, 6, 7, 9, 7, 8, 8, 3, 3, 7, 8, 2, 2, 4,
4, 5, 3, 4, 1, 5, 5, 1]
plt.ylabel('PMF')
sns.histplot(samp, stat='probability', bins=20);