📖 All & Any
a = np.arange(10)
a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
# any : 하나라도 조건에 만족한다면 true
np.any(a>5), np.any(a<0)
(True, False)
# all : 모두가 조건에 만족한다면 true
np.all(a>5), np.all(a<10)
(False, True)
📖 comparison operation #1
test_a = np.array([1, 3, 0], float)
test_b = np.array([5, 2, 1], float)
test_a > test_b
array([False, True, False])
test_a == test_b
array([False, False, False])
# any : 하나라도 true라면 true
(test_a > test_b).any()
True
📖 comparison operation #2
a = np.array([1, 3, 0], float)
# and 조건의 condition
np.logical_and(a > 0, a < 3)
array([ True, False, False])
b = np.array([True, False, True], bool)
# NOT 조건의 condition
np.logical_not(b)
array([False, True, False])
c = np.array([False, True, False], bool)
# OR 조건의 condition
np.logical_or(b, c)
array([ True, True, True])
📖 np.where
# where(condition, True, False)
np.where(a > 0, 3, 2)
array([3, 3, 2])
# Index 값 반환
a = np.arange(10)
np.where(a>5)
(array([6, 7, 8, 9]),)
# nan : not a number
a = np.array([1, np.NaN, np.Inf], float)
np.isnan(a)
array([False, True, False])
# isfinite : is finite number
np.isfinite(a)
array([ True, False, False])
📖 argmax & argmin
a = np.array([1,2,4,5,8,78,23,3])
np.argmax(a) ,np.argmin(a)
(5, 0)
a = np.array([[1,2,4,7],[9,88,6,45],[9,76,3,4]])
np.argmax(a, axis=1), np.argmin(a, axis=0)
(array([3, 1, 1]), array([0, 0, 2, 2]))
📖 boolean index
test_array = np.array([1, 4, 0, 2, 3, 8, 9, 7], float)
test_array > 3
array([False, True, False, False, False, True, True, True])
# 조건이 True인 index의 element만 추출
test_array[test_array > 3]
array([4., 8., 9., 7.])
condition = test_array < 3
test_array[condition]
array([1., 0., 2.])
📖 fancy index
a = np.array([2, 4, 6, 8], float)
# 반드시 integer로 선언
b = np.array([0, 0, 1, 3, 2, 1], int)
# bracket index, b 배열의 값을 index로 하여 a의 값들을 추출함
a[b]
array([2., 2., 4., 8., 6., 4.])
# take 함수 : bracket index와 같은 효과
a.take(b)
array([2., 2., 4., 8., 6., 4.])
a = np.array([[1, 4],[9, 16]], float)
b = np.array([0, 0, 1, 1, 0], int)
c = np.array([0, 1, 1, 1, 1], int)
# b를 row index, c를 column index로 변환하여 표시함
a[b,c]
array([ 1., 4., 16., 16., 4.])
# b를 row index로 변환하여 표시
a[b]
array([[ 1., 4.], [ 1., 4.], [ 9., 16.], [ 9., 16.], [ 1., 4.]])
📖 loadtxt & savetxt
# 파일 호출
a = np.loadtxt("./populations.txt")
# int type으로 변환
a_int = a.astype(int)
# int_data.csv로 저장
np.savetxt('int_data.csv', a_int, delimeter=',')
<이 게시물은 최성철 교수님의 numpy 강의 자료를 참고하여 작성되었습니다.>
본 포스트의 학습 내용은 [부스트캠프 AI Tech 5기] Pre-Course 강의 내용을 바탕으로 작성되었습니다.
부스트캠프 AI Tech 5기 Pre-Course는 일정 기간 동안에만 운영되는 강의이며,
AI 관련 강의를 학습하고자 하시는 분들은 부스트코스 AI 강좌에서 기간 제한 없이 학습하실 수 있습니다.
(https://www.boostcourse.org/)