728x90
반응형
Numpy Exercise
Create a boolean array
np.full((3,3), True, dtype=bool)
array([[ True, True, True],
[ True, True, True],
[ True, True, True]])
np.full(shape, fill_value, dtype=None)
- shape : 생성할 array의 shape을 지정
- fill_value : 생성할 array의 값을 지정
- dtype : 생성할 array의 자료형(data type)을 지정
Stack arrays a and b vertically
a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)
np.concatenate([a,b], axis=0)
np.r_[a,b]
array([[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[1, 1, 1, 1, 1],
[1, 1, 1, 1, 1]])
np.concatenate((a1, a2, ...), axis=0)
- a1, a2, ... : 같은 shape의 array를 지정
- axis : 합치고 싶은 축 지정
Stack arrays a and b horizontally
a = np.arange(10).reshape(2,-1)
b = np.repeat(1, 10).reshape(2,-1)
np.concatenate([a,b], axis=1)
np.c_[a,b]
array([[0, 1, 2, 3, 4, 1, 1, 1, 1, 1],
[5, 6, 7, 8, 9, 1, 1, 1, 1, 1]])
Get all items between 5 and 10 from a.
a = np.array([2, 6, 1, 9, 10, 3, 27])
index = np.where((a>=5) & (a<=10))
a[index]
a[(a>=5) & (a<=10)]
array([6, 9, 10])
np.where(condition, x, y)
- condition : 적절한 조건
- x : condition이 True이면 x를 반환
- y : condition이 False이면 y를 반환
- x, y가 주어지지 않는다면 condition을 만족하는 index를 반환
Create the ranks for the given numeric array a.
np.random.seed(10)
a = np.random.randint(20, size=10)
print(a)
print(a.argsort()) # 각 값을 오름차순 하여 index를 반환
a.argsort().argsort() # 한 번 더 진행하게 되면 각 값에 맞는 rank를 반환
array([9, 4, 15, 0, 17, 16, 17, 8, 9, 0])
array([3, 9, 1, 7, 0, 8, 2, 5, 4, 6])
array([4, 2, 6, 0, 8, 7, 9, 3, 5, 1])
np.argsort(a, axis=-1)
- a : array 를 지정
- axis : 정렬하고 싶은 축 지정
Compute the one-hot encodings (dummy binary variables for each unique value in the array)
np.random.seed(101)
arr = np.random.randint(1,4, size=6)
def one_hot(arr):
unique_value = np.unique(arr)
counts = len(unique_value)
value_to_index = {value: idx for idx, value in enumerate(unique_value)}
return np.eye(counts)[[value_to_index[value] for value in arr]]
one_hot(arr)
[2 3 2 2 2 1]
array([[0., 1., 0.],
[0., 0., 1.],
[0., 1., 0.],
[0., 1., 0.],
[0., 1., 0.],
[1., 0., 0.]])
np.eye(N, M=None, k=0) : 주어진 크기의 단위 행렬 or 대각 행렬을 생성
- N : row의 수
- M : column의 수
- k : 대각 행렬 값이 시작하는 위치
np.unique(ar, return_index=False, return_inverse=False, return_counts=False)
- ar : array를 지정
- return_index : True이면 array에서 unique한 값이 처음 나온 index 반환
- return_inverse : True이면 array에서 unique한 값에 매칭되는 index 반환
- return_counts : True이면 array에서 unique한 값의 횟수 반환
REF
https://www.machinelearningplus.com/python/101-numpy-exercises-python/
728x90
반응형