Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python绘制熊猫系列的CDF_Python_Pandas_Series_Cdf - Fatal编程技术网

用python绘制熊猫系列的CDF

用python绘制熊猫系列的CDF,python,pandas,series,cdf,Python,Pandas,Series,Cdf,有办法做到这一点吗?我似乎不是一个简单的方法来连接熊猫系列和绘制CDF 我相信您正在寻找的功能是在Series对象的hist方法中,该方法将hist()函数包装在matplotlib中 这是相关的文件 In [10]: import matplotlib.pyplot as plt In [11]: plt.hist? ... Plot a histogram. Compute and draw the histogram of *x*. The return value is a tupl

有办法做到这一点吗?我似乎不是一个简单的方法来连接熊猫系列和绘制CDF

我相信您正在寻找的功能是在Series对象的hist方法中,该方法将hist()函数包装在matplotlib中

这是相关的文件

In [10]: import matplotlib.pyplot as plt

In [11]: plt.hist?
...
Plot a histogram.

Compute and draw the histogram of *x*. The return value is a
tuple (*n*, *bins*, *patches*) or ([*n0*, *n1*, ...], *bins*,
[*patches0*, *patches1*,...]) if the input contains multiple
data.
...
cumulative : boolean, optional, default : True
    If `True`, then a histogram is computed where each bin gives the
    counts in that bin plus all bins for smaller values. The last bin
    gives the total number of datapoints.  If `normed` is also `True`
    then the histogram is normalized such that the last bin equals 1.
    If `cumulative` evaluates to less than 0 (e.g., -1), the direction
    of accumulation is reversed.  In this case, if `normed` is also
    `True`, then the histogram is normalized such that the first bin
    equals 1.

...
比如说

In [12]: import pandas as pd

In [13]: import numpy as np

In [14]: ser = pd.Series(np.random.normal(size=1000))

In [15]: ser.hist(cumulative=True, density=1, bins=100)
Out[15]: <matplotlib.axes.AxesSubplot at 0x11469a590>

In [16]: plt.show()
[12]中的
:将熊猫作为pd导入
在[13]中:将numpy作为np导入
[14]中:ser=pd.系列(np.随机.正常(尺寸=1000))
在[15]中:序列历史(累积=真,密度=1,箱数=100)
出[15]:
In[16]:plt.show()

CDF或累积分布函数图基本上是一个图形,X轴上显示排序值,Y轴上显示累积分布。因此,我将创建一个新的序列,其中排序值作为索引,累积分布作为值

首先创建一个示例系列:

import pandas as pd
import numpy as np
ser = pd.Series(np.random.normal(size=100))
对序列进行排序:

ser = ser.sort_values()
现在,在继续之前,再次追加最后一个(也是最大的)值。为了获得无偏CDF,这一步骤特别重要,尤其是对于小样本量:

ser[len(ser)] = ser.iloc[-1]
创建一个新系列,将排序值作为索引,将累积分布作为值:

cum_dist = np.linspace(0.,1.,len(ser))
ser_cdf = pd.Series(cum_dist, index=ser)
最后,将函数绘制为以下步骤:

ser_cdf.plot(drawstyle='steps')

对我来说,这似乎是一种简单的方法:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

heights = pd.Series(np.random.normal(size=100))

# empirical CDF
def F(x,data):
    return float(len(data[data <= x]))/len(data)

vF = np.vectorize(F, excluded=['data'])

plt.plot(np.sort(heights),vF(x=np.sort(heights), data=heights))
将numpy导入为np
作为pd进口熊猫
将matplotlib.pyplot作为plt导入
高度=局部放电系列(np.随机.正常(尺寸=100))
#经验CDF
def F(x,数据):

返回浮点(len)(data[数据这是最简单的方法

import pandas as pd
df = pd.Series([i for i in range(100)])
df.hist( cumulative = True )

我来这里是想找一个这样的带有条形图和CDF线的图:

可以这样实现:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
series = pd.Series(np.random.normal(size=10000))
fig, ax = plt.subplots()
ax2 = ax.twinx()
n, bins, patches = ax.hist(series, bins=100, normed=False)
n, bins, patches = ax2.hist(
    series, cumulative=1, histtype='step', bins=100, color='tab:orange')
plt.savefig('test.png')
如果要删除垂直线,则说明如何完成。或者您可以执行以下操作:

ax.set_xlim((ax.get_xlim()[0], series.max()))

我还看到了一个关于如何使用seaborn的优雅解决方案,我在“纯”熊猫中找到了另一个解决方案,它不需要在直方图中指定要使用的箱子数量:

import pandas as pd
import numpy as np # used only to create example data

series = pd.Series(np.random.normal(size=10000))

cdf = series.value_counts().sort_index().cumsum()
cdf.plot()

如果您也对值感兴趣,而不仅仅是绘图

将熊猫作为pd导入
#如果你在jupyter
%matplotlib内联
这将始终有效(离散和连续分布)
#定义您的系列
s=pd.Series([9,5,3,5,5,4,6,5,5,8,7],name='value')
df=pd.数据帧
#获取序列中每个值的频率、PDF和CDF
#频率
统计数据_df=df\
.groupby(“值”)\
[“价值”]\
.agg('计数')\
.管道(pd.数据帧)\
.rename(列={'value':'frequency'})
#PDF
统计数据df['pdf']=统计数据df['frequency']/sum(统计数据df['frequency'])
#CDF
stats_df['cdf']=stats_df['pdf'].cumsum()
stats\u df=stats\u df.reset\u index()
统计数字

#绘制离散概率质量函数和CDF。
#从技术上讲,图例和表格中的“pdf标签”应为“pmf”
#(概率质量函数)因为分布是离散的。
#如果你没有太多的值/通常是离散的情况
stats_df.plot.bar(x='value',y=['pdf','cdf'],grid=True)

另一个示例是从连续分布中提取的样本,或者您有许多单独的值:

#定义您的系列
s=pd.系列(np.随机.正常(loc=10,刻度=0.1,大小=1000),名称='value')
#…所有相同的计算工具都可以得到频率、PDF、CDF
#绘图
统计图(x='value',y=['pdf','cdf'],grid=True)

仅适用于连续分布 请注意如果假设样本中每个值只出现一次是非常合理的(通常在连续分布的情况下会遇到),那么
groupby()
+
agg('count')
就没有必要了(因为计数总是1)

在这种情况下,可以使用百分比排名直接访问cdf

在走这种捷径时,请使用您的最佳判断!:)

#定义您的系列
s=pd.系列(np.随机.正常(loc=10,刻度=0.1,大小=1000),名称='value')
df=pd.数据帧
#直接进入CDF
df['cdf']=df.rank(方法='average',pct=True)
#排序和打印
df.sort_值('value').plot(x='value',y='cdf',grid=True)

如果你想要绘制一个“真实”的经验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'
调用确保跳转发生在它们应该发生的地方。要强制以最小的数据值跳转,代码会在
x
y
前面插入一个附加元素

用法示例:

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'])
输出:


你能定义你的问题吗?输入和输出是什么?scipy.stats有你可能感兴趣的cdf函数。有一个功能请求,但它不属于熊猫的领域。使用的
kdeplot
cumulative=True
输入是一个序列,输出是cdf函数的绘图。当我签出seaborn时,我得到了is error“累积分布当前在statsmodels中实现。请安装statsmodels。”如果可能的话,请尝试添加一些描述和链接来备份代码。有没有一种方法可以只获取step函数而不填充条形图?那就是
histtype='step'
,它也在
pyplot.hist
文档中,上面被截断了。这很好。除了上面提到的方法之外,是否还有一个选项来规范化x轴从0到1或从0到100?为什么需要附加最后一个值?
顺序
已被弃用。请使用
ser.sort_values()
@kadee
ser[len(ser)]=ser.iloc[-1]
对熊猫0.19不起作用。这是答案,它非常详细且有用。Nic