본문 바로가기
기타

[빅데이터분석기사] 5회 기출 변형

by 돌맹96 2023. 12. 2.
728x90
반응형
# 작업 1유형
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p1_1_.csv')
df.head(5)

## Q1-1 20L가격과 5L가격이 모두 0원이 아닌 데이터만 필터를 한 후, 각 row별로 20L가격과 5L가격의 차이를 ‘차이가격’ 이라 부른다고 하자. 시도명 별 차이가격의 평균가격을 비교할때 그 값이 가장 큰 금액을 반올림하여 소숫점 이하 1자리까지 구하여라
total = df[(df['20L가격'] != 0) & (df['5L가격'] != 0)]
total['차이가격'] = total['20L가격'] - total['5L가격']
r = total.groupby(['시도명'])['차이가격'].mean().sort_values().to_frame()
result = r['차이가격'].max().round(1)
print(result)


import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p1_2_.csv')
df.head(5)
# Q1-2 BMI는 몸무게(kg) / (키(M) * 키(M)) 로 정의 된다. 초고도 비만은 BMI 25이상 , 고도 비반은 BMI 25미만 - 23이상 , 정상은 23미만 - 18.5이상 저체중은 18.5미만으로 정의 된다. 주어진 데이터에서 초고도비만 인원 + 저체중 인원 의 숫자는?
print(df)
df['BMI'] = df['weight(kg)'] / (df['height(cm)'] * df['height(cm)']) * 10000


def change(x):
    if(x >= 25):
        return '초고도비만'
    elif(x>=23 and x<25):
        return '고도비만'
    elif(x >= 18.5 and x < 23):
        return '정상'
    else:
        return '저체중'

df['BMI_category'] = df['BMI'].map(change)

result = df[df.BMI_category.isin(['초고도비만', '저체중'])].shape[0]
print(result)

# 작업 2유형
# 벤츠 차량 가격 예측 : https://www.kaggle.com/datasets/mysarahmadbhat/mercedes-used-car-listing train = https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p2_train_.csv test = https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p2_test_.csv
#
# 예측 변수 price, test.csv에 대해 ID별로 price 값을 예측하여 제출, 제출 데이터 컬럼은 ID와 price 두개만 존재해야함. 평가지표는 rmse
import pandas as pd
train = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p2_train_.csv')
test = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p2_test_.csv')

test.head(2)

train_x_drop = train.drop(['ID', 'price'], axis=1)
train_y_drop = train['price']

test_x_drop = test.drop(['ID'], axis=1)


train_x_dummies = pd.get_dummies(train_x_drop)
test_x_dummies = pd.get_dummies(test_x_drop)
test_x_dummies = test_x_dummies.reindex(columns=train_x_dummies.columns, fill_value=0)

from sklearn.model_selection import train_test_split
X_train,X_val , Y_train, Y_val = train_test_split(train_x_dummies, train_y_drop, test_size=0.2)

from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error
import numpy as np
rf = RandomForestRegressor()
rf.fit(X_train, Y_train)
pre = rf.predict(X_val)
print('rsme : ', np.sqrt(mean_squared_error(Y_val,pre)))

pre_test = rf.predict(test_x_dummies)
sumission = pd.DataFrame()
sumission['ID'] = test['ID']
sumission['price'] = pre_test
sumission.head()
sumission.to_csv('test.csv', index=False)
# 작업 3유형
import pandas as pd
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p3_1.csv')
df.head()

## 3-1-a 55명 학생들의 키에 대한 표본 평균을 구하여라(반올림하여 소숫점 3째자리까지
height = df['height'].mean()
mean = round(height, 3)
print(mean)

## 3-1-b t분포 양쪽 꼬리에서의 t 값을 구하여라 (반올림하여 소수4째자리까지)
from scipy.stats import t
import numpy as np

std = np.std(df.height, ddof=1)
n = len(df.height)

# 신뢰수준, 자유도
confidence_level = 0.95
ddof = n -1

# t 분포의 양쪽 꼬리에서의 t 값
t_value = round(t.ppf((1+confidence_level) / 2, ddof), 4)
print(t_value)

## 3-1-c 95% 신뢰구간을 구하여라(print(lower,upper) 방식으로 출력, 각각의 값은 소숫점 이하 3째자리까지)
#신뢰구간 계산
lower = round(mean-t_value * std / np.sqrt(n), 3)
upper = round(mean+t_value * std / np.sqrt(n), 3)

# A,B,C 세 공장에서 생산한 동일한 제품의 길이 데이터 이다. DataUrl = https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p3_2.csv 공장간의 제품 길이 차이가 유의미한지 확인 하려한다.
import pandas as pd
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e5_p3_2.csv')

## Q3-1-a 3 그룹의 데이터에 대해 크루스칼-왈리스 검정을 사용하여 검정 통계량을 반올림하여 소숫점 이하 3자리까지 구하여라
from scipy.stats import kruskal
df_A = df[df['ID'] == 'A']
df_B = df[df['ID'] == 'B']
df_C = df[df['ID'] == 'C']
statistic = kruskal(df_A['value'], df_B['value'], df_C['value']).statistic
print(round(statistic, 3))

## Q3-1-b 3 그룹의 데이터에 대해 크루스칼-왈리스 검정을 사용하여 p-value를 반올림하여 소숫점 이하 3자리까지 구하여라. 귀무가설과 대립가설중 0.05 유의수준에서 유의한 가설을 출력하라
p_value = kruskal(df_A['value'], df_B['value'], df_C['value']).pvalue
# 유의수준보다 작으면 대립 크면 귀무
print(round(p_value,3))
print('대립')
728x90
반응형