[Python] collections 모듈의 Counter 메서드

tacowasabii·2024년 6월 13일
0

Python

목록 보기
7/12
post-thumbnail

Python의 collections 모듈에는 다양한 유용한 자료 구조가 포함되어 있으며, 그 중 하나가 Counter 클래스이다. Counter는 요소의 개수를 세는 데 유용한 데이터 구조로, 주로 데이터의 빈도 분석에 사용된다. 아래는 Python Counter 클래스의 사용법과 다양한 기능에 대한 설명이다.


1. Counter 기본 사용법

Counter 객체를 생성하려면 collections 모듈에서 이를 가져와야 한다. 생성자에 반복 가능한(iterable) 객체를 전달하여 각 요소의 개수를 셀 수 있다.

from collections import Counter

# 리스트를 사용하여 Counter 객체 생성
data = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
counter = Counter(data)
print(counter)
# 출력: Counter({'apple': 3, 'banana': 2, 'orange': 1})

2. 문자열에서 Counter 사용

Counter는 문자열에서도 유용하게 사용할 수 있다. 각 문자의 빈도를 셀 수 있다.

text = "hello world"
counter = Counter(text)
print(counter)
# 출력: Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})

3. 딕셔너리에서 Counter 사용

기존 딕셔너리를 Counter 객체로 변환할 수 있다. 딕셔너리의 값들은 각 키의 개수로 간주된다.

data = {'apple': 3, 'banana': 2, 'orange': 1}
counter = Counter(data)
print(counter)
# 출력: Counter({'apple': 3, 'banana': 2, 'orange': 1})

4. Counter 메서드 및 기능

  • elements(): Counter 객체의 요소를 반복 가능한 객체로 반환한다.
counter = Counter({'apple': 3, 'banana': 2})
elements = list(counter.elements())
print(elements)
# 출력: ['apple', 'apple', 'apple', 'banana', 'banana']
  • most_common(n): 가장 빈도가 높은 n개의 요소와 그 빈도를 반환한다. n을 생략하면 모든 요소를 빈도 순으로 정렬하여 반환한다.
counter = Counter({'apple': 3, 'banana': 2, 'orange': 1})
common = counter.most_common(2)
print(common)
# 출력: [('apple', 3), ('banana', 2)]
  • subtract(iterable_or_mapping): 요소를 빼는 연산을 수행한다. iterable이나 mapping을 인자로 받아 요소의 빈도를 뺀다.
counter = Counter({'apple': 3, 'banana': 2})
counter.subtract({'apple': 1, 'banana': 1, 'orange': 1})
print(counter)
# 출력: Counter({'apple': 2, 'banana': 1, 'orange': -1})
  • update(iterable_or_mapping): 요소를 추가하는 연산을 수행한다. iterable이나 mapping을 인자로 받아 요소의 빈도를 더한다.
counter = Counter({'apple': 3, 'banana': 2})
counter.update(['apple', 'banana', 'banana', 'orange'])
print(counter)
# 출력: Counter({'apple': 4, 'banana': 4, 'orange': 1})
  • clear(): 모든 요소를 제거한다.
counter = Counter({'apple': 3, 'banana': 2})
counter.clear()
print(counter)
# 출력: Counter()

5. 산술 및 집합 연산

Counter는 산술 및 집합 연산도 지원한다. +, -, &, | 연산자를 사용하여 Counter 객체 간의 연산을 수행할 수 있다.

counter1 = Counter({'apple': 3, 'banana': 2})
counter2 = Counter({'apple': 1, 'banana': 2, 'orange': 1})

# 덧셈
print(counter1 + counter2)
# 출력: Counter({'apple': 4, 'banana': 4, 'orange': 1})

# 뺄셈
print(counter1 - counter2)
# 출력: Counter({'apple': 2})

# 교집합
print(counter1 & counter2)
# 출력: Counter({'apple': 1, 'banana': 2})

# 합집합
print(counter1 | counter2)
# 출력: Counter({'apple': 3, 'banana': 2, 'orange': 1})

Python의 Counter 클래스는 데이터의 빈도를 분석하고 관리하는 데 매우 유용한 도구이다. 다양한 메서드와 연산을 지원하여 데이터를 효율적으로 처리할 수 있다. 이를 통해 데이터를 더욱 쉽게 분석하고 관리할 수 있다.

profile
웹 프론트엔드 엔지니어

0개의 댓글

관련 채용 정보