• 회원가입
  • 로그인
  • 구글아이디로 로그인

[numpy] PY - NumPy Filter Array (배열 필터링) ★

8284  

목차

  1. 배열 필터링 정의
  2. 필터링 List 생성해 배열 필터링
  3. 필터링 배열 생성해 배열 필터링

 

배열 필터링 정의

 

필터링 뜻: 기존 배열에서 일부 요소를 가져 와서 새 배열 생성.

  • 필터링 List (= 참거짓 색인 List) 사용해 필터링.
  • 필터링 List : 배열 색인 각각에 대응하는 참거짓 List
  • True 경우, 배열에 포함 O 의미.
  • False 경우, 배열에 포함 X 의미.

 

cf.

배열 자르기 : 배열의 일부 구간의 요소만 선택.

 


[예제] 참거짓 색인 List 값이 True인 값으로 구성된 배열 반환.

 

import numpy as np

arr = np.array([1, 2, 3, 4])

x = arr[[True, False, True, False]]

print(x)

 

결과값: [1 3]

 

필터링 List 생성해 배열 필터링

 

위 예제 경우, 참거짓을 일일이 하나하나 적어줬으나,

일반적인 경우엔 지정 조건에 기반해 참거짓을 결정함.

 


[예제1] 배열 값이 2보다 큰 요소로 구성된 배열 생성.

 

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


# 참거짓 색인 List용 빈 List 생성.

filter_list = [] 


# 배열 요소 각각에 대해 노출 여부 결정.

for x in arr:

  if x > 2:

    filter_list.append(True)

  else:

    filter_list.append(False)

 

# 필터링 된 배열 생성.

newarr = arr[filter_list]


print(filter_list) # [False, False, True, True, True]

print(newarr) # [3 4 5]

 


[예제2] 배열 값이 짝수인 요소로 구성된 배열 생성.

 

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


filter_list = [] 


for x in arr:

  if x % 2 == 0:

    filter_list.append(True)

  else:

    filter_list.append(False)


newarr = arr[filter_list]


print(filter_list) # [False, True, False, True, False]

print(new_arr) # [2 4]


※ 필터링 배열을 생성하면 더 간단. (아래 참고.)

 

필터링 배열 생성해 배열 필터링

[예제1] 2보다 큰 값으로 구성된 배열. (= 위 예제1 비교)

 

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


filter_arr = arr > 2

newarr = arr[filter_arr]


print(filter_arr) # [False False  True  True  True]

print(newarr) # [3 4 5]

 


[예제2] 짝수 값으로 구성된 배열 생성. (※ 위 예제2 비교.)

 

import numpy as np

arr = np.array([1, 2, 3, 4, 5])


filter_arr = arr % 2 == 0

newarr = arr[filter_arr]


print(filter_arr) # [False  True False  True False]

print(newarr) # [2 4]

 



분류 제목
module Python - math.erf() 메서드 -
module Python - math.erfc() 메서드 -
module Python - math.exp() 메서드 -
module Python - math.expm1() 메서드 -
module Python - math.fabs() 메서드 -
module Python - math.factorial() 메서드 -
module Python - math.floor() 메서드 ★ - 바닥 반올림 (= 하위 정수로 반올림. = floor메…
module Python - math.fmod() 메서드 -
module Python - math.frexp() 메서드 -
module Python - math.fsum() 메서드 -
module Python - math.gamma() 메서드 -
module Python - math.gcd() 메서드 -
module Python - math.hypot() 메서드 -
module Python - math.isclose() 메서드 -
module Python - math.isfinite() 메서드 - 숫자 유한 여부 체크 (= math.isfinite메…
module Python - math.isinf() 메서드 -
module Python - math.isnan() 메서드 ★ - NaN 여부 체크. (= isnan메서드 = 이즈난메서…
module Python - math.isqrt() 메서드 -
module Python - math.ldexp() 메서드 -
module Python - math.lgamma() 메서드 -
20/24
목록
찾아주셔서 감사합니다. Since 2012