Numpy 개수 세기 - Numpy gaesu segi

koos808

Python

Python Numpy Function Part2 - 파이썬 넘파이 함수

koos808 2020. 11. 14. 01:40

  • Numpy 배열 길이 확인 방법

    • data.shape or len(data)
  • Numpy의 around() 함수

    • 반올림 함수
      • np.round(data, 2) or np.around(data, 2) 사용
  • Numpy 배열에서 원소(value) 몇 개씩 존재하는지 count(R에서의 table)

      # example 1
      from collections import Counter
      Counter(jaffe_Y)
    
      # example 2
      result = Counter(jaffe_Y)
      print(result)
      for key in result:
          print(key, result[key])
    
      # example 3
      import numpy as np
      x = np.array([1,1,1,2,2,2,5,25,1,1])
      y = np.bincount(x)
      ii = np.nonzero(y)[0]
      Zip(ii,y[ii]) # [(1, 5), (2, 3), (5, 1), (25, 1)]
    
      # example 4 : 키 없이 카운트 한 값만 알아내고 싶을 때 사용
      result = Counter(jaffe_Y).values()
      print(result)
  • Numpy 배열에서 어떤 값이 중복됐는지 확인하는 방법

      # 1. 중복된 값만 추출
      from collections import Counter
      a = np.array([1, 2, 1, 3, 3, 3, 0])
      [item for item, count in Counter(a).items() if count > 1]
    
      # 2. 중복된 값의 인덱스 추출
      u, c = np.unique(a, return_counts=True)
      dup = u[c > 1]
    
      # 3. 유니크한 값만 가져오기
      np.unique(data)
    • 2D, 3D... array에서 중복된 값 제거하고 가져오는 방법
        L = [np.array([1, 2, 3]), np.array([]), np.array([3, 2, 1]),
            np.array([1, 3, 2]), np.array([1, 2, 3]), np.array([1, 3, 2]),
            np.array([]), np.array([]), np.array([1, 2, 3]),np.array([7,7,7])]
        L
        `np.unique(L, axis=0)`
      • 참고 : https://docs.scipy.org/doc/numpy-1.14.0/reference/generated/numpy.unique.html
    • 응용 : A 변수에서 중복된 데이터 제외한 인덱스를 가져와 B 변수 select
      • u, indices = np.unique(fer2013_X, axis=0, return_index = True) -> fer2013_label = fer2013_label[indices]

numpy array는 count함수를 갖지 않는다.
이땐 collections 라이브러리를 사용한다.

예제

import numpy as np
import collections

coin= ['앞면','뒷면']
for _ in range(5):
    case = np.random.choice(coin,8)
    print(collections.Counter(case)['뒷면'])
    # Counter함수/array이름/찾고자하는 요소 이름

Numpy 개수 세기 - Numpy gaesu segi
TITLE
👀 배열 원소 수 세는 방법 ( count() / collections.Counter() ) 👀
1.list.count(x) : 배열 내 주어진 원소 x의 갯수를 셉니다. x가 포함된 원소가 아닌, x 자체만 셈. 문자열 가능
2.collections.Counter(배열, 문자열)  : 배열, 문자열 내 모든 원소의 갯수 셈. x가 포함된 원소가 아닌, x 자체만 셈. 딕셔너리도 가능. 

파이썬에서 배열 내원소의 갯수를 세는 방법으로는 다음과 같이 2개의 방법이 존재합니다.

collections 모듈의 Counter() 클래스와, 리스트 자체의 count() 함수가 있습니다.

1. count() -> list.count(x)

  • 배열 내에서 어떤 원소 x가 등장하는 횟수를 반환함.
  • x가 포함된 원소가 아닌 x 본연의 원소의 숫자만을 셈.
array = ['a', 'b', 'c', 'ae', 'ba', 'dab']
cnt = array.count('a')
print('배열 내 a의 등장 횟수 :', cnt)
# > 배열 a의 등장 횟수 : 1
  • 문자열(String)에도 적용 가능. 
string = 'abacaca'
cnt = string.count('a')
print('문자열 내 a의 등장 횟수 :', cnt)
# > 문자열 a의 등장 횟수 : 4

2. collections.Counter() -> counter = Counter(변수)

  • count와 마찬가지로 배열, 문자열, 둘다 사용 가능
  • 어떤 값 x 하나가 아닌 내 모든 단일 값의 갯수를 세어줌.
from collections import Counter

cnt = Counter(['a', 'b', 'c', 'ae', 'ba', 'dab'])
print('배열 내 각 원소를 세는 카운터 :', cnt)
# > 배열 내 각 원소의 갯수 : Counter({'a': 1, 'b': 1, 'c': 1, 'ae': 1, 'ba': 1, 'dab': 1})

cnt = Counter('Abracadabra!')
print('문자열 내 각 원소를 세는 카운터 :', cnt)
# 문자열 내 각 원소를 세는 카운터 : Counter({'a': 4, 'b': 2, 'r': 2, 'A': 1, 'c': 1, 'd': 1, '!': 1})
  • 원소별 접근 방법: cnt['x']
cnt = Counter('Abracadabra!')
print('a 의 갯수는 :', cnt['a'])
# > a 의 갯수는 : 4
  • 최다 빈도 원소 내림차순으로 n개 확인 가능: most_common(n)
cnt = Counter('Abracadabra!')
print('가장 많이 있는 원소 차례대로 3개 뽑기 :', cnt.most_common(3))
# > 가장 많이 있는 원소 차례대로 3개 뽑기 : [('a', 4), ('b', 2), ('r', 2)]
print('가장 빈도수가 높은 원소는?! :', cnt.most_common(1))
# > 가장 빈도수가 높은 원소는?! : [('a', 4)]
  • dictionary에도 사용가능.
cnt = Counter({'hi': 3, 'im': 4, 'dev': 9, 'fennec': 101})
print('문자열 내 각 원소를 세는 카운터 :', cnt)
# > 문자열 내 각 원소를 세는 카운터 : Counter({'fennec': 101, 'dev': 9, 'im': 4, 'hi': 3})

count() 함수는 배열에 대해 특정 원소의 갯수만을 추출할 때 사용한다고 보면 되고, collections.Counter()는 모든 원소의 갯수를 셀 때 도움이 됩니다. 목적에 따라 다르게 사용하면 될 것 같습니다.😊 (다만 collections.Counter()는 더욱 다양한 함수들이 있으니, 잘 확인하고 사용하면 많은 도움이 될 것 같습니다.)

<참고>

docs.python.org/ko/3/library/array.html?highlight=count#array.array.count

docs.python.org/ko/3/library/collections.html?highlight=collections#collections.Counter