我们可以使用
创建 ECDFimport numpy as np
from statsmodels.distributions.empirical_distribution import ECDF
ecdf = ECDF([3, 3, 1, 4])
然后在
点获得 ECDFecdf(x)
但是,如果我想知道 97.5% 百分位的 x 该怎么办?
从
http://www.statsmodels.org/stable/generated/statsmodels.distributions.empirical_distribution.ECDF.html?highlight=ecdf
来看,好像没有实施。
有什么办法可以做到这一点吗?或者还有其他库吗?
这是我的建议。线性插值,因为 dfs 只能从相当大的样本中有效估计。可以获得插值线段,因为它们的端点出现在样本中的不同值处。
import statsmodels.distributions.empirical_distribution as edf
from scipy.interpolate import interp1d
import numpy as np
import matplotlib.pyplot as plt
sample = [1,4,2,6,5,5,3,3,5,7]
sample_edf = edf.ECDF(sample)
slope_changes = sorted(set(sample))
sample_edf_values_at_slope_changes = [ sample_edf(item) for item in slope_changes]
inverted_edf = interp1d(sample_edf_values_at_slope_changes, slope_changes)
x = np.linspace(0.1, 1)
y = inverted_edf(x)
plt.plot(x, y, 'ro', x, y, 'b-')
plt.show()
print ('97.5 percentile:', inverted_edf(0.975))
它产生以下输出,
97.5 percentile: 6.75
numpy.quantile(x, q=.975)
将返回数组 x 中 ecdf 为 0.975 的值。
pandas.quantile(q=0.97)
。
它插值是正确的,但插值是在您正在使用的 x 周围的 2 个点之间,而不是 x 的最小值和最大值。
来自 Numpy 文档
可选的
method
参数指定当
所需的分位数位于两个索引 i
和 j = i + 1
之间。
来自 Pandas 文档
插值:{'线性','较低','较高','中点','最近'} 此可选参数指定要使用的插值方法, 当所需的分位数位于两个数据点
i
和 j
之间时:
* linear: `i + (j - i) * fraction`, where `fraction` is the