본문 바로가기

자격증공부/빅데이터분석기사

[빅데이터분석기사] 모의고사 5 (누적합, 결측치, 이상치, 정렬, 회귀, 정규분포검증)

320x100

 

[유형1-1] 누적합, 결측치 처리

(문제) 주어진 데이터에서 f2컬럼이 1인 조건에 해당하는 데이터의 f1컬럼 누적합을 계산한다. 이때 발생하는 누적합 결측치는 바로 뒤의 값을 채우고, 누적합의 평균값을 출력한다. (단, 결측치 바로 뒤의 값이 없으면 다음에 나오는 값을 채워넣는다.)

 

ㅇ 문제 바로가기(캐글)

 

* 누적합 : df.cumsum()

* 결측치 앞/뒤 값으로 채우기 : df.fillna(method = "bfill/ffill")

 

(풀이)

import pandas as pd
df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv')

# print(df.head(2))
# print(df.shape)
# print(df.info())

# 누적합
cond = df['f2'] == 1
# print(df[cond])
print(df[cond]['f1'].cumsum()) # 정답
# print(dir(df)) #cumsum
# print(help(df.cumsum))

# 누적합 결측치는 바로 뒤의 값으로 채우기
df2 = df[cond]['f1'].cumsum()
# print(df2.head(10))
df2 = df[cond]['f1'].cumsum().fillna(method = "bfill")
# print(df2.head(10))
# print(help(df.fillna))
#   We can also propagate non-null values forward or backward.
#     >>> df.fillna(method="ffill")
#         A   B   C   D
#     0   NaN 2.0 NaN 0
#     1   3.0 4.0 NaN 1
#     2   3.0 4.0 NaN 5
#     3   3.0 3.0 NaN 4

# 누적합의 평균값 출력
print(df2.mean())

 

[유형1-2] 수치형 변수 표준화

(문제) 주어진 데이터에서 f5 컬럼을 표준화(Standardization (Z - score Normalization)) 하고 그 중앙값을 구하시오.

- Standardization (Z-score Normalization)

 

ㅇ 문제 바로가기(캐글)

 

* from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()

df['컬럼'] = scaler.fit_transform(df[['컬럼']])

 

(풀이)

import pandas as pd
df = pd.read_csv('../input/bigdatacertificationkr/basic1.csv')

# print(df.shape)
# print(df.head(2))
# print(df.info())

from sklearn.preprocessing import StandardScaler
# print(help(sklearn.preprocessing.StandardScaler))
scaler = StandardScaler()
# print(help(StandardScaler()))
# print(help(StandardScaler().fit_transform))

df['f5'] = scaler.fit_transform(df[['f5']])
print(df['f5'].mean())

 

[유형1-3] 정렬, 이상치처리

(문제) 주어진 데이터에서 상위 10개 국가의 접종률 평균과 하위 10개 국가의 접종률 평균을 구하고, 그 차이를 구하세요.(단, 100%가 넘는 접종률 제거, 소수 첫째자리까지 출력)

 

ㅇ 문제 바로가기(캐글)

 

* 최대값으로 그룹합 : df.groupby(['컬럼']).max()

* 정렬(내림차순) : df.sort_values(by='컬럼', ascending = False)

 

(풀이)

import pandas as pd
df = pd.read_csv("../input/covid-vaccination-vs-death/covid-vaccination-vs-death_ratio.csv")

# print(df.shape)
# print(df.head(10))
# print(df.info())

# 국가별 접종률 구하기, 100% 넘는 접종률 제거
# print(help(df.groupby))
df2 = df.groupby(['country']).max()
# print(df2.head(), df2.shape) (197, 9)

# print(help(df.sort_values)) df.sort_values(by='col1', ascending=False)
df3 = df2.sort_values(by='ratio', ascending=False)
# print(df3.head())
cond = df3['ratio'] <= 100
df4 = df3[cond]
# print(df4['ratio'].head(10).mean())
# print(df4['ratio'].tail(10).mean())
max = df4['ratio'].head(10).mean()
min = df4['ratio'].tail(10).mean()
print(round((max-min),2))

 

[유형2] 보험료(회귀)

(문제) X_train, X_test, y_train 데이터 / target = 'charges' 예측하기

 

ㅇ 문제 바로가기(캐글)

 

(풀이)

####### 라이브러리, 데이터 읽기
import pandas as pd
# X_train = pd.read_csv('X_train.csv')
# y_train = pd.read_csv('y_train.csv')
# X_test = pd.read_csv('X_test.csv')

####### EDA
# print(X_train.shape, X_test.shape, y_train.shape) (1070, 7) (268, 7) (1070, 2)
# print(X_train.head(2))
# print(y_train.head(2))
# print(X_train.info())
# print(X_test.info())
# print(y_train.info())
# print(X_train.isnull().sum()) # 결측치 없음
# print(y_train.isnull().sum())

######## 데이터 전처리
# 학습에 불필요한 컬럼 제거 및 정리
# print(help(df.drop)) df.drop(['B', 'C'], axis=1)
X_train = X_train.drop(['id'], axis=1)
X_id = X_test.pop('id')
# print(X_train.shape) (1070, 6)
# print(help(df.pop)) df.pop('class')
# print(X_test.shape) (268, 6)

######## 피처엔지니어링
# 수치형/범주형 데이터 분리
n_train = X_train.select_dtypes(exclude = 'object').copy()
n_test = X_test.select_dtypes(exclude = 'object').copy()
c_train = X_train.select_dtypes(include = 'object').copy()
c_test = X_test.select_dtypes(include = 'object').copy()

# 수치형 - 컬럼정의 > MinMaxScaler
ncols = ['age', 'bmi', 'children']
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler()
n_train[ncols] = scaler.fit_transform(n_train[ncols])
n_test[ncols] = scaler.transform(n_test[ncols])
# print(X_train[cols].head(2))
# print(X_test[cols].head(2))

# 범주형 - 컬럼정의 > train/test 합쳐서 원핫인코딩 > 다시 분리
ccols = ['sex', 'smoker', 'region']
all_df = pd.concat([c_train[ccols], c_test[ccols]])
all_df = pd.get_dummies(all_df[ccols])
# # print(all_df.shape) (1338, 3)
# # print(help(pd.get_dummies)) / s1 = ['a', 'b', np.nan] /  pd.get_dummies(s1)
line = int(c_train[ccols].shape[0])
# print(line)
c_train = all_df.iloc[:line,:].copy()
c_test = all_df.iloc[line:,:].copy()
# print(c_train.shape, c_test.shape)
# print(c_train.head())
# print(help(pd.concat()))
# print(dir(pd))get_dummies

# 수치형/범주형 합쳐서 X_train, X_test 다시 만들기
X_train = pd.concat([n_train, c_train], axis=1 )
X_test = pd.concat([n_test, c_test], axis=1)
# print (X_train.shape, X_test.shape)

######## 학습/평가 데이터분리 > 모델생성 > 평가해서 선택
# 학습/평가용 데이터 분리
from sklearn.model_selection import train_test_split
X_tr, X_val, y_tr, y_val = train_test_split(X_train,
                                           y_train['charges'],
                                           test_size = 0.2,
                                           random_state = 2022
                                            )
# print(X_tr.shape, X_val.shape, y_tr.shape, y_val.shape)

# 평가방법 : 
from sklearn.metrics import r2_score
# print(help(r2_score)) r2_score(y_true, y_pred)

# 랜덤포레스트_XGB
# print(help(XGBRegressor))
from xgboost import XGBRegressor
model = XGBRegressor()
model.fit(X_tr, y_tr)
pred = model.predict(X_val)

# print(r2_score(y_val, pred)) 0.8163834836921064

######## 제출 DF 파일 생성
pred = model.predict(X_test)
# print(pred)
submit = pd.DataFrame({
    'id': X_id,
    'charges' : pred
})
# print(submit)
submit.to_csv('0000.csv', index=False)

 

 

[유형3] Shapiro Wilk 검정을 사용해서 정규분포 여부 검증하기

(문제) 12명의 수험생이 빅데이터 분석기사 시험에서 받은 점수이다. Shapiro-Wilk 검정을 사용하여 데이터가 정규분포를 따르는지 검증하시오. 검정통계량/p_valu/검정결과를 구하시오.

 - 귀무가설(H0) : 데이터는 정규분포를 따른다.

 - 대립가설(H1) : 데이터는 정규분포를 따르지 않는다.

 

ㅇ 문제 바로가기(캐글)

 

(풀이)

import pandas as pd
from scipy import stats

data = [75, 83, 81, 92, 68, 77, 78, 80, 85, 95, 79, 89]

# print(dir(stats))
# print(help(stats.shapiro))

stat, p_val = stats.shapiro(data)
print(stat, p_val)

# 검정통계량
print(stat)

# p_value
print(p_val)

#검증결과
print("p_valu가 0.05보다 크므로 귀무가설을 채택한다. 데이터는 정규분포를 따른다.")

 

320x100
반응형