如何绘制样本的PMF?(How to plot a PMF of a sample?)

编程入门 行业动态 更新时间:2024-10-26 07:39:32
如何绘制样本的PMF?(How to plot a PMF of a sample?)

是否有任何函数或库可以帮助我绘制样本的概率质量函数,就像绘制样本的概率密度函数一样?

例如,使用熊猫,绘制PDF就像调用一样简单:

sample.plot(kind="density")

如果没有简单的方法,我如何计算PMF,以便使用matplotlib进行绘图?

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 ?

For instance, using pandas, plotting a PDF is as simple as calling:

sample.plot(kind="density")

If there is no easy way, how can I compute the PMF so I could plot using matplotlib ?

最满意答案

如果ts是一个系列,您可以通过以下方式获得样本的PMF:

>>> pmf = ts.value_counts().sort_index() / len(ts)

并按以下方式绘制

>>> pmf.plot(kind='bar')

numpy唯一的解决方案可以使用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]])

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 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]])

更多推荐

本文发布于:2023-08-01 03:37:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1354029.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:样本   PMF   sample   plot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!