基于列中的元素存储和打印ECDF值

2024-05-19 02:09:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧df

df=

index  value
A      1
B      4
C      8
D      3
E      12
F      7

如何找到df['value']列中每个元素的经验累积分布函数(ECDF),并将相应值存储在单独的df['ecdf']列中。ECDF的公式为:

enter image description here

更多关于ECDF的文档可以在here中找到。我还对绘制获得的CDF的折线图感兴趣

预期输出:

df=

index  value  ecdf
A      1      0.1667
B      4      0.5
C      8      0.8333
D      3      0.3333
E      12     1
F      7      0.6667

Tags: 数据函数文档元素dfindexherevalue
2条回答

使用^{}通过nmethod=max(分配组中的最高秩)计算数值数据秩,并使用^{}除以value中的项数:

df['ecdf'] = df['value'].rank(method='max').div(df['value'].count())

结果:

  index  value      ecdf
0     A      1  0.166667
1     B      4  0.500000
2     C      8  0.833333
3     D      3  0.333333
4     E     12  1.000000
5     F      7  0.666667

只需使用numpymatplotlib即可绘制CDF:

import numpy as np
import matplotlib.pyplot as plt

sample = df['value'].values
x = np.sort(sample)
y = np.arange(1,len(x)+1)/float(len(x))
plt.plot(x, y)

输出:

enter image description here

相关问题 更多 >

    热门问题