Numpy

[Numpy] Fancy index

ju_young 2021. 7. 16. 16:04
728x90
In [2]:
import numpy as np
 
In [4]:
test_array = np.array([1, 4, 0, 2, 3, 8, 9, 7], float)
test_array > 3
Out[4]:
array([False,  True, False, False, False,  True,  True,  True])
 
In [6]:
test_array[test_array>3]
Out[6]:
array([4., 8., 9., 7.])
 
In [8]:
condition = test_array < 3
test_array[condition]
Out[8]:
array([1., 0., 2.])
 
In [10]:
A = np.array([
[12, 13, 14, 12, 16, 14, 11, 10,  9],
[11, 14, 12, 15, 15, 16, 10, 12, 11],
[10, 12, 12, 15, 14, 16, 10, 12, 12],
[ 9, 11, 16, 15, 14, 16, 15, 12, 10],
[12, 11, 16, 14, 10, 12, 16, 12, 13],
[10, 15, 16, 14, 14, 14, 16, 15, 12],
[13, 17, 14, 10, 14, 11, 14, 15, 10],
[10, 16, 12, 14, 11, 12, 14, 18, 11],
[10, 19, 12, 14, 11, 12, 14, 18, 10],
[14, 22, 17, 19, 16, 17, 18, 17, 13],
[10, 16, 12, 14, 11, 12, 14, 18, 11],
[10, 16, 12, 14, 11, 12, 14, 18, 11],
[10, 19, 12, 14, 11, 12, 14, 18, 10],
[14, 22, 12, 14, 11, 12, 14, 17, 13],
[10, 16, 12, 14, 11, 12, 14, 18, 11]])
B = A < 15
B.astype(np.int)
Out[10]:
array([[1, 1, 1, 1, 0, 1, 1, 1, 1],
       [1, 1, 1, 0, 0, 0, 1, 1, 1],
       [1, 1, 1, 0, 1, 0, 1, 1, 1],
       [1, 1, 0, 0, 1, 0, 0, 1, 1],
       [1, 1, 0, 1, 1, 1, 0, 1, 1],
       [1, 0, 0, 1, 1, 1, 0, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 0, 0, 0, 0, 0, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1],
       [1, 0, 1, 1, 1, 1, 1, 0, 1]])
 
In [15]:
a = np.array([2, 4, 6, 8], float)
b = np.array([0,0,1,3,2,1], int)
 
In [13]:
a[a>5]
Out[13]:
array([6., 8.])
 
In [17]:
a.take(b) #index에 해당하는 값을 가져옴
Out[17]:
array([2., 2., 4., 8., 6., 4.])
 
In [18]:
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]
Out[18]:
array([ 1.,  4., 16., 16.,  4.])
 
In [19]:
a = np.array([[1, 4], [9, 16]], float)
a[b]
Out[19]:
array([[ 1.,  4.],
       [ 1.,  4.],
       [ 9., 16.],
       [ 9., 16.],
       [ 1.,  4.]])
728x90