在Python中绘制Pandas Series的CDF

69

有没有一种方法可以做到这一点?我似乎找不到一种简单的方法将pandas序列与绘制CDF相接口。


2
你能描述一下你的问题吗?输入和输出是什么?scipy.stats库中有一些你可能感兴趣的cdf函数。 - K.Chen
7
有一个功能请求,但它不在 pandas 的领域之内。使用 seabornkdeplot 并将 cumulative=True - TomAugspurger
输入是一系列数据,输出是累积分布函数的图形。 - wolfsatthedoor
2
当我查看seaborn时,出现了这个错误:“累积分布目前仅在statsmodels中实现。请安装statsmodels。” - wolfsatthedoor
11个回答

0
如果您想绘制一个“真实”的经验CDF,它在数据集a的值处准确跳跃,并且每个值的跳跃比例与该值的频率成正比,NumPy具有内置函数来完成这项工作:
import matplotlib.pyplot as plt
import numpy as np

def ecdf(a):
    x, counts = np.unique(a, return_counts=True)
    y = np.cumsum(counts)
    x = np.insert(x, 0, x[0])
    y = np.insert(y/y[-1], 0, 0.)
    plt.plot(x, y, drawstyle='steps-post')
    plt.grid(True)
    plt.savefig('ecdf.png')

unique() 的调用会按照已排序的顺序返回数据值及其相应频率。在 plot() 调用中使用选项 drawstyle='steps-post',确保跳跃发生在正确位置。为了在最小数据值处强制进行跳跃,代码在 xy 前面插入了一个额外的元素。

用法示例:

xvec = np.array([7,1,2,2,7,4,4,4,5.5,7])
ecdf(xvec)

另一种用法:

df = pd.DataFrame({'x':[7,1,2,2,7,4,4,4,5.5,7]})
ecdf(df['x'])

输出结果为:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接