本文介绍了如何绘制样本的PMF?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何函数或库可以帮助我绘制样本的概率质量函数,就像绘制样本的概率密度函数一样?
Is there any function or library that would help me to plot a probability mass function of a sample the same way there is for plotting the probability density function of a sample ?
例如,使用熊猫,绘制PDF就像调用一样简单:
For instance, using pandas, plotting a PDF is as simple as calling:
sample.plot(kind="density")
如果没有简便的方法,我该如何计算PMF,以便可以使用matplotlib进行绘图?
If there is no easy way, how can I compute the PMF so I could plot using matplotlib ?
推荐答案
如果ts
是一个序列,则可以通过以下方式获得样本的PMF:
If ts
is a series, you may obtain PMF of the sample by:
>>> pmf = ts.value_counts().sort_index() / len(ts)
并通过以下方式进行绘制:
and plot it by:
>>> pmf.plot(kind='bar')
仅numpy解决方案可以使用 np.unique
:
numpy only solution can be done using 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]])
这篇关于如何绘制样本的PMF?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!