python - 按百分位数对 python 字典进行排名

标签 python numpy dictionary

如果我有一个字典记录随机对象的计数频率:

dict = {'oranges': 4 , 'apple': 3 , 'banana': 3 , 'pear' :1, 'strawberry' : 1....}

我只想要频率位于前 25% 的键,我该怎么做?特别是如果它是一个非常长的尾部列表并且很多记录将具有相同的计数。

最佳答案

使用 collections.Counter对象并利用其 most_common方法返回频率最高的键,达到所需的百分位数。

对于第 25 个百分位数,将字典的长度除以 4 并将该值传递给 most_common:

>>> from collections import Counter
>>> dct = {'oranges': 4 , 'apple': 3 , 'banana': 3 , 'pear' :1, 'strawberry' : 1}
>>> c = Counter(dct)
>>> [tup[0] for tup in c.most_common(len(dct)//4)]
['oranges']

请注意,该百分位数中具有相同频率的潜在元素将被任意选择。

关于python - 按百分位数对 python 字典进行排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40096826/

相关文章:

python - 带有鲜花的 Tensorflow 示例

python - tensorflow 将 tf.int32 转换为 tf.string 在适合 Google 云 ml-engine 的版本中

python - Pandas 使用startswith从Dataframe中选择

python - 使用键作为元组高效循环字典

python - 在 python 中存储字典和 json 文件类型的推荐方法是什么

python - 计算特定员工的工资总和

python - 如何从网页中嵌入的 Tableau 图表中抓取工具提示值

python - 使用 Numpy 逐元素矩阵的阶乘

python - numpy.sum 的内部结构

python - 将字典列表解压到 pandas 数据框中的列表中