python - 从 numpy digitize 计算 bin 的百分位数?

标签 python pandas numpy histogram percentage

我有一组数据和一组用于创建 bin 的阈值:

data = np.array([0.01, 0.02, 1, 1, 1, 2, 2, 8, 8, 4.5, 6.6])
thresholds = np.array([0,5,10])
bins = np.digitize(data, thresholds, right=True)

对于 bins 中的每个元素,我想知道基本百分位数。例如,在 bins 中,最小的 bin 应该从第 0 个百分位数开始。然后是下一个 bin,例如第 20 个百分位数。因此,如果 data 中的值介于 data 的第 0 个和第 20 个百分位数之间,则它属于第一个 bin

我研究过 pandas rank(pct=True) 但似乎无法正确完成此操作。

建议?

最佳答案

您可以按照之前的 StackOverflow 问题 (Map each list value to its corresponding percentile) 中的描述计算数据数组中每个元素的百分位数。

import numpy as np
from scipy import stats
data = np.array([0.01, 0.02, 1, 1, 1, 2, 2, 8, 8, 4.5, 6.6])

方法 1:使用 scipy.stats.percentileofscore :

data_percentile = np.array([stats.percentileofscore(data, a) for a in data])
data_percentile
Out[1]:
array([  9.09090909,  18.18181818,  36.36363636,  36.36363636,
        36.36363636,  59.09090909,  59.09090909,  95.45454545,
        95.45454545,  72.72727273,  81.81818182])

方法 2:使用 scipy.stats.rankdata并标准化为 100(更快):

ranked = stats.rankdata(data)
data_percentile = ranked/len(data)*100
data_percentile
Out[2]:
array([  9.09090909,  18.18181818,  36.36363636,  36.36363636,
        36.36363636,  59.09090909,  59.09090909,  95.45454545,
        95.45454545,  72.72727273,  81.81818182])

现在您有了一个百分位数列表,您可以像以前一样使用 numpy.digitize 对它们进行分类:

bins_percentile = [0,20,40,60,80,100]
data_binned_indices = np.digitize(data_percentile, bins_percentile, right=True)
data_binned_indices
Out[3]:
array([1, 1, 2, 2, 2, 3, 3, 5, 5, 4, 5], dtype=int64)

这会根据您选择的百分位数列表的索引为您提供分箱的数据。如果需要,您还可以使用 numpy.take 返回实际(上)百分位数。 :

data_binned_percentiles = np.take(bins_percentile, data_binned_indices)
data_binned_percentiles
Out[4]:
array([ 20,  20,  40,  40,  40,  60,  60, 100, 100,  80, 100])

关于python - 从 numpy digitize 计算 bin 的百分位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39308146/

相关文章:

python - 如何在不启动 Jupyter Notebook 服务器的情况下使用 .ipynb 文件?

python - Django 模板剥离空格?

python - Pandas - value_counts() 中消失的值

pandas - 在 Pandas 数据框中查找一组子字符串的计数

python - 如何在 Python shell 中导入 NumPy

python - 在 NumPy 中复制 Matlab 的 ISMEMBER 函数的索引结果?

python - 不和谐.py : How do I get the name of the user who triggers on_member_update?

python - statsmodel python库中ccf函数的解读

pandas - 如何计算列表数据的计数和首次出现?

python - Scipy 的复数最小平方