Python中使用Counter统计序列最高频元素的方法
本文介绍Python中用于统计序列元素出现频率的Counter类。通过示例演示如何利用collections模块中的Counter类,结合most_common()方法快速获取列表或字符串中出现次数最多的元素。同时讲解了Counter对象支持加减运算的高级功能,适用于词频统计等数据分析场景。
前言
Python提供了6种内置序列类型,包括列表、元组、字符串、Unicode字符串、buffer对象以及xrange对象。序列中的每个元素都拥有唯一的索引编号。列表与元组的主要区别在于可变性:列表支持修改,而元组不可修改。在绝大多数场景中,元组都可以被列表替代,唯一的例外情况是当元组作为字典的键使用时,由于字典键必须不可变,此时不能使用列表。
在统计分析或数据处理过程中,经常需要统计序列中出现频率最高的元素。例如,在英文文本分析中,查询出现次数最多的词汇及其具体频次。常规做法是将每个元素作为字典的键,每出现一次就将对应的值加1。
例如:
morewords = ['why','are','you','not','looking','in','my','eyes'] for word in morewords: word_counts[word] += 1
collections.Counter 类是专为解决此类计数问题而设计的,它甚至提供了一个非常有用的most_common()方法,可以直接返回统计结果。
collections模块
collections模块自Python 2.4版本起引入,除了标准的dict、set、list和tuple外,还提供了一些特殊的容器类型,具体包括:
- OrderedDict类:排序字典,继承自字典,自Python 2.7版本引入。
- namedtuple()函数:命名元组工厂函数,自Python 2.6版本引入。
- Counter类:用于对hashable对象进行计数,继承自字典,自Python 2.7版本引入。
- deque:双向队列,自Python 2.4版本引入。
- defaultdict:利用工厂函数创建字典,自动处理缺失的键,自Python 2.5版本引入。
相关文档参见:http://docs.python.org/2/library/collections.html。
Counter类
Counter类的核心功能是跟踪值出现的次数。它是一个无序容器,以字典键值对形式存储数据,其中元素作为key,计数值作为value。计数值可以是任意整数(包括0和负数)。Counter类与其他语言中的bags或multisets概念相似。
为了演示,假设有一个单词列表,想要找出出现频率最高的单词。操作方式如下:
words = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under'
]
from collections import Counter
word_counts = Counter(words)
# 出现频率最高的3个单词
top_three = word_counts.most_common(3)
print(top_three)
# Outputs [('eyes', 8), ('the', 5), ('look', 4)]
此外,collections.Counter还支持更高级的功能,允许使用数学算术符号进行相加和相减运算。
>>> a = Counter(words)
>>> b = Counter(morewords)
>>> a
Counter({'eyes': 8, 'the': 5, 'look': 4, 'into': 3, 'my': 3, 'around': 2,
"you're": 1, "don't": 1, 'under': 1, 'not': 1})
>>> b
Counter({'eyes': 1, 'looking': 1, 'are': 1, 'in': 1, 'not': 1, 'you': 1,
'my': 1, 'why': 1})
>>> # Combine counts
>>> c = a + b
>>> c
Counter({'eyes': 9, 'the': 5, 'look': 4, 'my': 4, 'into': 3, 'not': 2,
'around': 2, "you're": 1, "don't": 1, 'in': 1, 'why': 1,
'looking': 1, 'are': 1, 'under': 1, 'you': 1})
>>> # Subtract counts
>>> d = a - b
>>> d
Counter({'eyes': 7, 'the': 5, 'look': 4, 'into': 3, 'my': 2, 'around': 2,
"you're": 1, "don't": 1, 'under': 1})
>>>
参考文档:
https://docs.python.org/3/library/collections.html
总结
以上就是本文的全部内容,希望这些内容对您的学习或工作有所帮助。如有任何疑问,欢迎留言交流,感谢支持。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









