numpy part III

Numpy part III



comparison

All & Any

  • Array의 데이터 전부(and) 또는 일부(or)가 조건에 만족 여부 반환
In [1]:
import numpy as np
In [2]:
a = np.arange(10)
a
Out[2]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [3]:
a < 4
Out[3]:
array([ True,  True,  True,  True, False, False, False, False, False,
       False])
In [4]:
np.all(a < 10)
Out[4]:
True
  • all: 모든 조건에 만족하면 True, 아니면 False
In [5]:
np.any(a > 5), np.any(a < 0)
Out[5]:
(True, False)

image.png

In [6]:
np.all(a > 5), np.all(a < 10)
Out[6]:
(False, True)

image.png


대소 비교

  • numpy는 배열의 크기가 동일 할 때,
    element간 비교의 결과를 Boolean type으로 반환
In [7]:
test_a = np.array([1, 3, 0], float)
test_b = np.array([5, 2, 1], float)
In [8]:
test_a > test_b
Out[8]:
array([False,  True, False])
In [9]:
(test_a > test_b).any()
Out[9]:
True
In [10]:
a = np.array([1, 3, 0], float)
a > 0
Out[10]:
array([ True,  True, False])
In [11]:
print(np.logical_and(a>0,a<3)) # and조건의 condition
print((a>0)&(a<3))
[ True False False]
[ True False False]
  • logical_and()&와 같다
In [12]:
b = np.array([True, False, True], bool)
print(np.logical_not(b))  # Not 조건의 condition
print(~b)
[False  True False]
[False  True False]
  • logical_not()~와 같다
In [13]:
c = np.array([False, True, False], bool)
print(np.logical_or(b, c))  # OR 조건의 condition
print(b|c)
[ True  True  True]
[ True  True  True]
  • logical_or()|와 같다


np.where

  • np.where(condition,True,False) → 바뀐 값이 반환
  • np.where(condition) → 해당 조건 index 반환
In [14]:
a=np.arange(10)
a
Out[14]:
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
In [15]:
np.where(a > 5, 3, 2)  # where(condition, TRUE, FALSE)
Out[15]:
array([2, 2, 2, 2, 2, 2, 3, 3, 3, 3])
In [16]:
np.where(a > 5)   # index 반환
Out[16]:
(array([6, 7, 8, 9], dtype=int64),)


np.isnan()

  • np.nan값이면 True, 아니면 False
In [17]:
a = np.array([1, np.NaN, np.Inf], float)
np.isnan(a)
Out[17]:
array([False,  True, False])


np.isfinite()

  • 발산하는 값이 아니면 True, 맞으면 False
  • np.inf무한을 나타내는 발산 값이다.
  • np.nan은 의미로는 data값이 없음을 의미하지만 값으로 보면 발산 값이다.
In [18]:
np.isfinite(a)
Out[18]:
array([ True, False, False])


argmax & argmin

  • Array내 최대값 또는 최소값의 index를 반환
In [19]:
a = np.array([1, 2, 4, 5, 8, 78, 23, 3])
In [20]:
np.argmax(a), np.argmin(a)
Out[20]:
(5, 0)

argsort()

  • 정렬후 해당 원소의 index반환
In [21]:
a.argsort()[::]
Out[21]:
array([0, 1, 7, 2, 3, 4, 6, 5], dtype=int64)
  • 오름차순으로 정렬후 해당 인덱스 반환
In [22]:
a.argsort()[::-1]
Out[22]:
array([5, 6, 4, 3, 2, 7, 1, 0], dtype=int64)
  • 내림차순으로 정렬후 해당 인덱스 반환

axis 기반의 반환

In [23]:
a = np.array([[1, 2, 4, 7], [9, 88, 6, 45], [9, 76, 3, 4]])
a
Out[23]:
array([[ 1,  2,  4,  7],
       [ 9, 88,  6, 45],
       [ 9, 76,  3,  4]])

image.png

In [24]:
np.argmax(a, axis=1), np.argmin(a, axis=0)
Out[24]:
(array([3, 1, 1], dtype=int64), array([0, 0, 2, 2], dtype=int64))



boolean & fancy index

boolean index

  • 특정 조건에 따른 값을 배열 형태로 추출
  • Comparison operation 함수들도 모두 사용 가능
In [25]:
test_array = np.array([1, 4, 0, 2, 3, 8, 9, 7], float)
test_array > 3
Out[25]:
array([False,  True, False, False, False,  True,  True,  True])
In [26]:
test_array[test_array > 3]
Out[26]:
array([4., 8., 9., 7.])
  • 조건이 True인 index의 element만 추출
In [27]:
condition = test_array < 3
test_array[condition]
Out[27]:
array([1., 0., 2.])


fancy index

  • numpy는 array를 index value로 사용해서 값 추출
  • 이때 index value로는 해당 array의 index범위값을 넘어서면 안된다
In [28]:
a = np.array([2, 4, 6, 8], float)
b = np.array([0,0,1,3,2,1],int)  # 반드시 integer로 선언
a[b]
Out[28]:
array([2., 2., 4., 8., 6., 4.])

image.png

In [29]:
a.take(b)  # take함수: bracket index와 같은 효과
Out[29]:
array([2., 2., 4., 8., 6., 4.])
  • take()함수의 사용으로 같은 효과
In [30]:
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)
a[b, c]  # b를 row index, c를 column index로 변환하여 표시함
Out[30]:
array([ 1.,  4., 16., 16.,  4.])

image.png

  • matrix 형태의 데이터도 가능
In [31]:
a = np.array([[1, 4], [9, 16]], float)
b = np.array([0, 0, 1, 1, 0], int)
a[b]  # 2D인데 하나 값만 있으므로 row값만 가지고 온다
Out[31]:
array([[ 1.,  4.],
       [ 1.,  4.],
       [ 9., 16.],
       [ 9., 16.],
       [ 1.,  4.]])



numpy data I/O

loadtxt & savetxt

In [32]:
data = np.loadtxt("./data/populations.txt", delimiter="\t")  # 파일 읽기
data
Out[32]:
array([[ 1900., 30000.,  4000., 48300.],
       [ 1901., 47200.,  6100., 48200.],
       [ 1902., 70200.,  9800., 41500.],
       [ 1903., 77400., 35200., 38200.],
       [ 1904., 36300., 59400., 40600.],
       [ 1905., 20600., 41700., 39800.],
       [ 1906., 18100., 19000., 38600.],
       [ 1907., 21400., 13000., 42300.],
       [ 1908., 22000.,  8300., 44500.],
       [ 1909., 25400.,  9100., 42100.],
       [ 1910., 27100.,  7400., 46000.],
       [ 1911., 40300.,  8000., 46800.],
       [ 1912., 57000., 12300., 43800.],
       [ 1913., 76600., 19500., 40900.],
       [ 1914., 52300., 45700., 39400.],
       [ 1915., 19500., 51100., 39000.],
       [ 1916., 11200., 29700., 36700.],
       [ 1917.,  7600., 15800., 41800.],
       [ 1918., 14600.,  9700., 43300.],
       [ 1919., 16200., 10100., 41300.],
       [ 1920., 24700.,  8600., 47300.]])
In [33]:
data_int= data.astype(int)
data_int_3=data_int[:3]
data_int_3
Out[33]:
array([[ 1900, 30000,  4000, 48300],
       [ 1901, 47200,  6100, 48200],
       [ 1902, 70200,  9800, 41500]])
In [34]:
np.savetxt("./data/int_data.csv", data_int, fmt="%.2e", delimiter=",")
  • int_data.csv로 저장


numpy object - npy

In [35]:
np.save("./data/npy_test.npy", arr=data_int_3)
  • numpy객체로 파일 저장
  • 해당 파일은 pickle형태이다
In [36]:
data_test=np.load(file='./data/npy_test.npy')
data_test
Out[36]:
array([[ 1900, 30000,  4000, 48300],
       [ 1901, 47200,  6100, 48200],
       [ 1902, 70200,  9800, 41500]])

'AI > 이론' 카테고리의 다른 글

경사하강법 II  (0) 2021.01.26
경사하강법 I  (0) 2021.01.26
행렬  (0) 2021.01.25
벡터  (0) 2021.01.25
Numpy part II  (0) 2021.01.25
Numpy part I  (0) 2021.01.25
Python data handling  (0) 2021.01.22
File & Exception & Log Handling  (0) 2021.01.22

+ Recent posts