Chapter2 Arithmetic Operations: Notebook5 Mean, Std and Var Values
우리가 data를 분석할 때 가장 먼저 사용하는 값들이 바로 mean, standard deviation, variance 값들이다.
물론 NumPy에서도 이를 쉽게 구할 수 있는 method들이 존재한다. 이들은 각각
1. ndarray.mean()
2. ndarray.std()
3. ndarray.var()
이다.
import numpy as np
ndarray.mean(), ndarray.std(), ndarray.var() with 1-dim ndarray¶
test_np = np.random.randint(low = 0, high = 100, size = (200,))
print("mean:", test_np.mean())
print("standard deviation: ", test_np.std())
print("variance:", test_np.var())
이를 이용하면 data에 대한 통계적 처리가 훨씬 수월해진다.
실제 예를 들기 위해 우리의 수학, 영어, 물리 성적을 가져와보자.
ndarray.mean(), ndarray.std(), ndarray.var() with 2-dim ndarray¶
이제 2차원 ndarray를 이용하여 mean, std, var를 구해보고 실제 수능과 같은 시험에서 사용되는 표준점수를 환산하는 과정을 살펴보자.
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)
우리가 mean, std, var를 구하는 과정은 과목별로 구하게 되므로 axis=0이 되는 것을 알 수 있고,
이는 각각 다음과 같다.
mean_np = score_table.mean(axis = 0)
std_np = score_table.std(axis = 0)
print("mean values:", mean_np)
print("std values:", std_np)
이때 slicing을 이용하여 각 점수들을 추출해보면
print(score_table.shape)
위와 같이 현재 20명에 대한 각각의 과목별 점수를 가지고 있다.
그리고 표준점수를 환산하는 공식은 다음과 같다.
표준점수 = $20*\frac{원점수- 과목평균}{과목표준편차} + 100$
구체적인 이유는 중요한 것이 아니므로 이 표준점수를 구하는 과정에 집중해보도록 하자
먼저 dimension을 살펴보면 다음과 같다.
print(score_table.shape)
print(mean_np.shape)
print(std_np.shape)
그리고 우리가 배운 broadcasting을 이요하면
score_table - mean_np
를 하면 mean_np는 (20,3)로 broadcasting되어 각각의 element에 element-wise로 빼지는 것을 알 수 있다.
mean_sub = score_table - mean_np
print(mean_sub.shape)
물론 이 결과는 다시 (20,3)의 ndarray를 가지게 되고, 우리가 여기에 std_np를 나눠준다면 다시 이 std_np는 (20,3)으로 broadcasting되어 나눠지는 것을 알 수 있다.
std_div = (score_table - mean_np)/std_np
print(std_div.shape)
그리고 우리가 matrix와 scalar의 연산에서의 broadcasting을 이용하여 20을 곱해주고, 100을 더해주면
원하는 표준점수의 ndarray를 구할 수 있다.
standard_scores = 20*(score_table - mean_np)/std_np + 100
print(standard_scores.shape)
이렇게 ndarray를 이용하면 한 줄을 통해 큰 matrix에 연산도 가능해지는 것을 알 수 있다.