欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python处理PDF与CDF实例

时间:2021-02-18 11:19:08|栏目:Python代码|点击:

在拿到数据后,最需要做的工作之一就是查看一下自己的数据分布情况。而针对数据的分布,又包括pdf和cdf两类。

下面介绍使用python生成pdf的方法:

使用matplotlib的画图接口hist(),直接画出pdf分布;

使用numpy的数据处理函数histogram(),可以生成pdf分布数据,方便进行后续的数据处理,比如进一步生成cdf;

使用seaborn的distplot(),好处是可以进行pdf分布的拟合,查看自己数据的分布类型;

上图所示为采用3种算法生成的pdf图。下面是源代码。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

arr = np.random.normal(size=100)

# plot histogram
plt.subplot(221)
plt.hist(arr)

# obtain histogram data
plt.subplot(222)
hist, bin_edges = np.histogram(arr)
plt.plot(hist)

# fit histogram curve
plt.subplot(223)
sns.distplot(arr, kde=False, fit=stats.gamma, rug=True)
plt.show()

下面介绍使用python生成cdf的方法:

使用numpy的数据处理函数histogram(),生成pdf分布数据,进一步生成cdf;

使用seaborn的cumfreq(),直接画出cdf;

上图所示为采用2种算法生成的cdf图。下面是源代码。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

arr = np.random.normal(size=100)

plt.subplot(121)
hist, bin_edges = np.histogram(arr)
cdf = np.cumsum(hist)
plt.plot(cdf)

plt.subplot(122)
cdf = stats.cumfreq(arr)
plt.plot(cdf[0])

plt.show()

在更多时候,需要把pdf和cdf放在一起,可以更好的显示数据分布。这个实现需要把pdf和cdf分别进行归一化。

上图所示为归一化的pdf和cdf。下面是源代码。

from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

arr = np.random.normal(size=100)

hist, bin_edges = np.histogram(arr)
width = (bin_edges[1] - bin_edges[0]) * 0.8
plt.bar(bin_edges[1:], hist/max(hist), width=width, color='#5B9BD5')

cdf = np.cumsum(hist/sum(hist))
plt.plot(bin_edges[1:], cdf, '-*', color='#ED7D31')

plt.xlim([-2, 2])
plt.ylim([0, 1])
plt.grid()

plt.show()

上一篇:python实现DNS正向查询、反向查询的例子

栏    目:Python代码

下一篇:python使用PIL模块实现给图片打水印的方法

本文标题:Python处理PDF与CDF实例

本文地址:http://www.codeinn.net/misctech/65179.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有