데이터 개수를 셀 때 유용한 파이썬의 collections 모듈의 Counter 클래스 사용법 ( 참고자료

* Counter() : 데이터 개수 세서 딕셔너리 형태로 반환

from collections import Counter

word_count = Counter('hello world') 
print(word_count)
>>> Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

for key,value in word_count.items():
    print(key,':',value)
>>> h : 1
>>> e : 1
>>> l : 3

 

* Counter의 내부 메소드

  • most_common() : Counter()에서 가장 빈도수가 높은 순으로 정렬
from collections import Counter

# 데이터의 개수가 많은 순으로 정렬된 배열 리턴
Counter('hello world').most_common() 
>>>[('l', 3), ('o', 2), ('h', 1), ('e', 1), (' ', 1), ('w', 1), ('r', 1), ('d', 1)]

# 가장 개수가 많은 k개의 데이터 리턴
Counter('hello world').most_common(1)
>>> [('l', 3)]

 

반응형

+ Recent posts