Python

[NumPy] NumPy 조건문

주댕이 2024. 1. 17. 12:58

# 단일 조건문

import numpy as np

np.where(condition, [x, y, ]/)
# condition: Where True, yield x, otherwise yield y.
# 배열 생성
arr = np.arange(10)
arr  # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# 0, 1, 2, 3, 4, 50, 60, 70, 80, 90으로 값 수정하기
np.where(arr < 5, arr, arr * 10)
# array([ 0,  1,  2,  3,  4, 50, 60, 70, 80, 90])

 

 

# 다중 조건문

np.select(condlist, choicelist, default=0)[source]
# condlist: The list of conditions which determine from which array in choicelist the output elements are taken.
#           When multiple conditions are satisfied, the first one encountered in condlist is used.
# choicelist: The list of arrays from which the output elements are taken. It has to be of the same length as condlist.
# default: The element inserted in output when all conditions evaluate to False.
# 100, 101, 2, 3, 4, 5, 12, 14, 16, 18로 값 수정하기
# 2 미만일 때는 100을 더하고, 5 초과일 때는 2를 곱하기

cond_list = [arr > 5, arr < 2]
choice_list = [arr * 2, arr + 100]

np.select(cond_list, choice_list, default = arr)
# array([100, 101,   2,   3,   4,   5,  12,  14,  16,  18])
728x90