관리 메뉴

물 만날 물고기

[python] Counter() 함수 본문

Python/파이썬 (python)

[python] Counter() 함수

Lung Fish 2023. 4. 6. 18:25

🔍 예상 검색어

더보기

# Counter() 함수 사용법

# python 개수 셀 때 사용하는 코드


해당 포스팅은 Counter() 함수 사용 예제에 대해서 정리하였습니다.

 

 

 Counter는 파이썬의 내장 모듈인 collections 모듈에 포함되어 있는 함수로, iterable(반복 가능한)한 객체 내부의 원소들의 개수를 셀 때 사용됩니다.

 

 1. 문자 개수 셀 때

from collections import Counter

s = "apple"
counter_s = Counter(s)
print(counter_s) 

>>> 출력결과
# Counter({'p': 2, 'a': 1, 'l': 1, 'e': 1})

 

 2. 내부 요소의 개수 셀 때

from collections import Counter

lst = [1, 2, 3, 1, 2, 1, 4, 5, 2, 2]
counter_lst = Counter(lst)
print(counter_lst)

>>> 출력결과
# Counter({2: 4, 1: 3, 3: 1, 4: 1, 5: 1})

 

3. 클래스 개수 셀 때 (불균형 확인)

from sklearn.datasets import load_iris
from collections import Counter

iris = load_iris()
y = iris.target

class_distribution = Counter(y)
print(class_distribution)  

>>> 출력결과
# Counter({0: 50, 1: 50, 2: 50})