레이블이 Counter인 게시물을 표시합니다. 모든 게시물 표시
레이블이 Counter인 게시물을 표시합니다. 모든 게시물 표시

2022년 10월 20일 목요일

파이썬 collections Counter

Collection의 Counter 함수는 array나 list에 해당 값이 얼마나 나왔는지 세는 함수입니다.

이 Counter object는 사실 dictionary를 inherit 한것이라,, dictionary형태를 지니고 있습니다

아래는 예제입니다.

from collections import Counter
sample = Counter([1,2,3,4,2,3,4,1,2,3])
print (sample[4])  # 2

위 결과는 4의 개수를 센 값이 나옵니다.

Counter는 실제 excel같은데서 많이들 사용하는 함수와 같은 유형이라, 생각보다 유용한 경우가 많이 있습니다.

counter 함수를 사용해 리스트의 개수세기

collections.Counter(a) : a에서 요소들의 개수를 세어, 딕셔너리 형태로 반환합니다. {문자 : 개수} 형태

import collections
b = [1,3,4,3,2,3,5,1,2,3,2,3,9]
a = [1,2,3,4,3,2,2,1,5,3,1,3,4,2,3]
print(collections.Counter(a) , collections.Counter(b))

# Counter({3: 5, 2: 4, 1: 3, 4: 2, 5: 1}) Counter({3: 5, 2: 3, 1: 2, 4: 1, 5: 1, 9: 1})

counter - 연산

counter 함수로 구한 딕셔너리의 값(value)끼리 연산이 가능합니다. 연산은 + , - , &(교집합), |(합집합) 네가지가 가능합니다. 서로 빼기 연산을 했을때 , 음수 값이 나오지는 않습니다. a list의 2, 3번이 나오지 않습니다

import collections
a = [1,1,1,1,2,3,1,1]
b = [1,1,2,2,2,2,3,3,3]

print(collections.Counter(a) - collections.Counter(b))
print(collections.Counter(a) + collections.Counter(b))
print(collections.Counter(a) & collections.Counter(b))
print(collections.Counter(a) | collections.Counter(b))

# Counter({1: 4})
# Counter({1: 8, 2: 5, 3: 4})
# Counter({1: 2, 2: 1, 3: 1})
# Counter({1: 6, 2: 4, 3: 3})

most_common() 함수 - 최빈값 구하기

most_common([n]) : 많이나오는 순서대로 상위부터 n개까지를 출력 (리스트에 담긴 튜플형태로)

import collections
a  = [1,1,1,2,3,2,3,1,4,2,2,2,45,9]

print(collections.Counter(a).most_common(3))
 
# [(2, 5), (1, 4), (3, 2)]

elements() : 모든 element의 list를 출력

import collections
a  = [1,1,1,2,3,2,3,1,4,2,2,2,45,9]

print(list(collections.Counter(a).elements()))
 
# [1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 4, 45, 9]

이상으로 collections의 Counter 메소드들을 정리해보았습니다.