수색…


iterable : collections.Counter의 모든 항목을 모두 계산합니다.

from collections import Counter

c = Counter(["a", "b", "c", "d", "a", "b", "a", "c", "d"])
c
# Out: Counter({'a': 3, 'b': 2, 'c': 2, 'd': 2})
c["a"]
# Out: 3

c[7]     # not in the list (7 occurred 0 times!)
# Out: 0

collections.Counter 는 반복 가능한 모든 요소에 사용할 수 있으며 모든 요소에 대해 모든 발생을 계산합니다.

참고 : 하나의 예외는 dict 또는 다른 collections.Mapping 과 같은 클래스가 주어지면 그 값을 계산하지 않고 다음 값이있는 카운터를 만듭니다.

Counter({"e": 2})
# Out: Counter({"e": 2})

Counter({"e": "e"})        # warning Counter does not verify the values are int
# Out: Counter({"e": "e"})

가장 일반적인 값 가져 오기 (-s) : collections.Counter.most_common ()

Mapping 를 계산하는 것은 collections.Counter Mapping 불가능하지만 값을 계산할 수 있습니다 .

from collections import Counter
adict = {'a': 5, 'b': 3, 'c': 5, 'd': 2, 'e':2, 'q': 5}
Counter(adict.values())
# Out: Counter({2: 2, 3: 1, 5: 3})

가장 일반적인 요소는 most_common -method에 있습니다.

# Sorting them from most-common to least-common value:
Counter(adict.values()).most_common()
# Out: [(5, 3), (2, 2), (3, 1)]

# Getting the most common value
Counter(adict.values()).most_common(1)
# Out: [(5, 3)]

# Getting the two most common values
Counter(adict.values()).most_common(2)
# Out: [(5, 3), (2, 2)]

시퀀스에서 한 항목의 발생 수 계산 : list.count () 및 tuple.count ()

alist = [1, 2, 3, 4, 1, 2, 1, 3, 4]
alist.count(1)
# Out: 3

atuple = ('bear', 'weasel', 'bear', 'frog')
atuple.count('bear')
# Out: 2
atuple.count('fox')
# Out: 0

문자열에서 부분 문자열의 출현 계산 : str.count ()

astring = 'thisisashorttext'
astring.count('t')
# Out: 4

이는 한 문자보다 긴 하위 문자열에도 적용됩니다.

astring.count('th')
# Out: 1
astring.count('is')
# Out: 2
astring.count('text')
# Out: 1

collections.Counter 에서는 불가능합니다. 한 문자 만 카운트하는 카운터 :

from collections import Counter
Counter(astring)
# Out: Counter({'a': 1, 'e': 1, 'h': 2, 'i': 2, 'o': 1, 'r': 1, 's': 3, 't': 4, 'x': 1})

numpy 배열로 발생 수 계산하기

numpy 배열에서 값의 발생을 계산합니다. 이것은 작동 할 것이다 :

>>> import numpy as np
>>> a=np.array([0,3,4,3,5,4,7])
>>> print np.sum(a==3)
2

논리는 boolean 문이 요청 된 값의 모든 발생이 1이고 다른 모든 값이 0 인 배열을 생성한다는 것입니다. 이렇게 합하면 발생 횟수가 달라집니다. 이것은 모든 모양이나 dtype의 배열에 적용됩니다.

numpy에서 모든 고유 값의 발생을 계산하는 데 사용하는 두 가지 방법이 있습니다. 고유 한 기능. Unique는 다차원 배열을 자동으로 평평하게합니다. bincount는 양의 정수 만 포함하는 1 차원 배열에서만 작동합니다.

>>> unique,counts=np.unique(a,return_counts=True)
>>> print unique,counts # counts[i] is equal to occurrences of unique[i] in a
[0 3 4 5 7] [1 2 2 1 1]
>>> bin_count=np.bincount(a)
>>> print bin_count # bin_count[i] is equal to occurrences of i in a
[1 0 0 2 2 1 0 1] 

데이터가 numpy 배열 인 경우 일반적으로 numpy 메소드를 사용하여 데이터를 일반 메소드로 변환하는 것이 훨씬 빠릅니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow