우리가 여태 ndarray의 method를 배웠던 것들은 다음과 같다.
1. ndarray.max()
2. ndarray.min()
3. ndarray.argmax()
4. ndarray.argmin()
5. ndarray.mean()
6. ndarray.std()
7. ndarray.var()
8. ndarray.T
9. ndarray.squeeze()
10. ndarray.dot()
하지만 많은 사람들은 ndarray의 method 외에도 numpy의 method를 많이 사용한다.
따라서 위의 함수들은 다음과 같이 사용할 수 있다.
1. np.max(ndarray)
2. np.min(ndarray)
3. np.argmax(ndarray)
4. np.argmin(ndarray)
5. np.mean(ndarray)
6. np.std(ndarray)
7. np.var(ndarray)
8. np.transpose(ndarray)
9. np.squeeze(ndarray)
10. np.dot(ndarray1, ndarray2)
각자의 장점이 있으므로 두 가지다 익혀두는 것이 좋다.
사용방법은 기존 ndarray의 method와 대부분 동일하니 표준점수를 구하는 과정을 복습하면서 차이점을 확인해보자.
In [1]:
import numpy as np
Standard Score with NumPy Methods¶
다시 한 번 해당 데이터를 불러와보자.
In [16]:
import pandas as pd
maths = np.random.randint(low = 30, high = 100, size = (20,))
english = np.random.randint(low = 30, high = 100, size = (20,))
physics = np.random.randint(low = 30, high = 100, size = (20,))
score_table = np.vstack((maths, english, physics)).T
d = {"Math scores": maths, "English scores": english, "Physics scores": physics}
df = pd.DataFrame(data=d)
print(df)
그리고 표준점수를 구하는 과정은
표준점수 = $20*\frac{원점수- 과목평균}{과목표준편차} + 100$
와 같았다.
위의 score_table에서 우리는 다음과 같이 mean, std를 구했다.
In [17]:
mean_np = score_table.mean(axis = 0)
std_np = score_table.std(axis = 0)
이를 NumPy 자체의 method를 이용하면
In [18]:
mean_np = np.mean(score_table, axis = 0)
std_np = np.mean(score_table, axis = 0)
가 되고, notebook5와 마찬가지로 표준점수를 구할 수 있다.
In [19]:
standard_scores = 20*(score_table - mean_np)/std_np + 100
Matrix Multiplications with NumPy Methods¶
우리가 matrix multiplication을 여러번 할 때 다음과 같이 했었다.
In [20]:
operand1 = np.random.randint(low=0, high=5, size=(2,3))
operand2 = np.random.randint(low=0, high=5, size=(3,4))
operand3 = np.random.randint(low=0, high=5, size=(4,2))
result = operand1.dot(operand2)
print(result.shape)
이를 NumPy method를 이용하면 다음과 같다.
In [22]:
operand1 = np.random.randint(low=0, high=5, size=(2,3))
operand2 = np.random.randint(low=0, high=5, size=(3,4))
operand3 = np.random.randint(low=0, high=5, size=(4,2))
result = np.dot(operand1, operand2)
result = np.dot(result, operand3)
print(result.shape)
이렇게 ndarray의 method와 NumPy의 method를 학습하는 이유는 사람들이 이 두 가지 방법을 모두 사용하기 때문이다.
참고로 저자는 NumPy의 method를 바로 사용하는 방법을 선호한다.
따라서 앞으로 NumPy의 method를 주로 사용할 예정이다.
'NumPy Master Class' 카테고리의 다른 글
Chapter3 Mathematical Functions: Notebook2 Hyperbolic Functions (0) | 2020.01.08 |
---|---|
Chapter3 Mathematical Functions: Notebook1 Trigonometric Functions (0) | 2020.01.08 |
Chapter2 Arithmetic Operations: Notebook7 Matrix Multiplications (0) | 2020.01.08 |
Chapter2 Arithmetic Operations: Notebook6 Dot Products (0) | 2020.01.08 |
Chapter2 Arithmetic Operations: Notebook5 Mean, Std and Var Values (0) | 2020.01.08 |