728x90
안녕하세요
오늘은 collections.Counter 로 데이터 갯수 세는 방법에 대해 알아보도록 하겠습니다
.
데이터 분석, 로그 처리, 텍스트 마이닝을 하다 보면
"이 값이 몇 번 나왔는지" 빈도수를 알고 싶을 때가 많습니다.
파이썬의 collections 모듈 안에 있는 Counter 클래스를 사용하면
이 작업을 아주 간단하게 처리할 수 있습니다.
전체 코드입니다.
main.py
from collections import Counter
# 1. 리스트에서 카운트하기
fruits = ["사과", "바나나", "사과", "포도", "바나나", "사과"]
# Counter 객체 생성 (리스트의 요소 개수를 자동으로 세어줌)
fruit_counter = Counter(fruits)
print("=== 과일 개수 세기 ===")
print(fruit_counter)
# 출력: Counter({'사과': 3, '바나나': 2, '포도': 1})
print("사과 개수:", fruit_counter["사과"]) # 특정 요소 개수 가져오기
print("오렌지 개수:", fruit_counter["오렌지"]) # 없는 값은 0으로 나옴
# 2. most_common() : 많이 나온 순으로 정렬
print("\n=== 가장 많이 나온 과일 ===")
print(fruit_counter.most_common(1)) # [('사과', 3)]
print(fruit_counter.most_common(2)) # [('사과', 3), ('바나나', 2)]
# 3. 문자열에서 단어 개수 세기
text = "apple banana apple kiwi banana apple"
words = text.split() # 공백 기준으로 분리
word_counter = Counter(words)
print("\n=== 단어 빈도수 ===")
print(word_counter)
# 출력: Counter({'apple': 3, 'banana': 2, 'kiwi': 1})
# 4. update()로 값 추가하기
print("\n=== update()로 카운트 추가 ===")
word_counter.update(["banana", "kiwi", "kiwi"])
print(word_counter)
# 출력: Counter({'apple': 3, 'banana': 3, 'kiwi': 3})
# 5. elements()로 원래 데이터 복원
print("\n=== elements() 사용 ===")
print(list(word_counter.elements()))
# 각 요소가 개수만큼 반복된 리스트로 출력
결과입니다.

'Python' 카테고리의 다른 글
| [Python] 이미지 임베딩으로 텍스트↔이미지 검색하기 (CLIP) (0) | 2025.10.02 |
|---|---|
| [Python] 간단히 구현하는 AI 이미지 캡셔닝 (Image Captioning) (0) | 2025.10.01 |
| [Python] 벡터 DB로 문장 검색하기 (Faiss 활용) (0) | 2025.09.29 |
| [Python] RAG(Retrieval-Augmented Generation) 이해하기 (0) | 2025.09.26 |
| [Python] 간단한 PDF 파일 만들기 (0) | 2025.09.24 |