6회 기출 변형#

Hits

광고 한번 눌러주세요 ㅎㅎ 모두 좋은 결과 있으시길 바랍니다.

작업 1유형#

Attention

DataUrl = https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e6_p1_1.csv 데이터 출처 : https://bigdata-119.kr/ 데이터 설명 : 소방신고별 신고시각과 출동시각 데이터 컬럼 설명 : 신고일자 (yyyymmdd) / 신고시각 (HHMMSS , 00시 , 00분의 경우 등 생략)

import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e6_p1_1.csv')
df.head(5)
구급보고서번호 소방서명 환자증상구분명1 신고일자 신고시각 출동일자 출동시각 환자직업명 사고발생장소
0 20211122103M01526 중랑소방서 심계항진 20210330 104800 20210330 105042 무직
1 20211111105M00771 노원소방서 복통 20210412 225600 20210412 225827 기타
2 20211115104M00864 서초소방서 심계항진 20210303 194100 20210303 194500 직장인 상업시설
3 20211113107M01869 마포소방서 고열 20211225 235400 20211226 331 유아
4 20211118102M05820 강동소방서 고열 20211019 12100 20211019 12322 무직

1-1

각 구급 보고서 별 출동시각과 신고시각의 차이를 ‘소요시간’ 컬럼을 만들고 초(sec)단위로 구하고 소방서명 별 소요시간의 평균을 오름차순으로 정렬 했을때 3번째로 작은 소요시간의 값과 소방서명을 출력하라

Hide code cell source
df['소요시각'] = (
                pd.to_datetime(
                    df['출동일자'].astype('str') + df['출동시각'].astype('str').str.zfill(6)
                )

                - 
    
                pd.to_datetime(
                    df['신고일자'].astype('str') + df['신고시각'].astype('str').str.zfill(6)
                )
                ).dt.total_seconds()


result = df.groupby(['소방서명'])['소요시각'].mean().sort_values().reset_index().iloc[2].values
print(result)
['종로소방서' 175.5]
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e6_p1_2.csv')
df.head(5)
학교명 시도 학교세부유형 일반학급_학생수_계 교원수_총계_계
0 서울대학교사범대학부설고등학교 서울 일반고등학교 689 73
1 가락고등학교 서울 일반고등학교 765 70
2 개포고등학교 서울 일반고등학교 684 69
3 경기고등학교 서울 일반고등학교 1047 96
4 경동고등학교 서울 일반고등학교 529 58

1-2

학교 세부유형이 일반중학교인 학교들 중 일반중학교 숫자가 2번째로 많은 시도의 일반중학교 데이터만 필터하여 해당 시도의 교원 한명 당 맡은 학생수가 가장 많은 학교를 찾아서 해당 학교의 교원수를 출력하라

Hide code cell source
city = df[df['학교세부유형'] =='일반중학교'].시도.value_counts().index[1]
filter_df = df[(df['학교세부유형'] =='일반중학교') & (df['시도'] ==city)].reset_index(drop=True)
filter_df.loc[:,'ratio'] = (filter_df['일반학급_학생수_계'] / filter_df['교원수_총계_계']).values
filter_df = filter_df.sort_values('ratio').dropna()
result= filter_df['교원수_총계_계'].values[-1]
print(result)
33
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/e6_p1_3.csv')
df.head(5)
범죄분류 절도 사기 배임 방화 폭행
0 2018년_1월 13280 25318 656 143 12186
1 2018년_2월 12504 19159 403 135 12087
2 2018년_3월 14733 24509 471 148 13841
3 2018년_4월 14781 23147 414 135 13973
4 2018년_5월 15988 23584 451 127 14117

1-3

**5대 범죄(절도, 사기, 배임, 방화, 폭행)의 월별 총 발생건수를 총범죄수라고 표현하자. 18,19년의 각각 분기별 총범죄수의 월평균 값을 구했을때 최대값을 가지는 년도와 분기를 구하고 해당 분기의 최댓값의 사기가 발생한 월의 사기 발생건수를 출력하라(1분기:1,2,3월 / 2분기 : 4,5,6월 / 3분기 7,8,9월 / 4분기 10,11,12월 , 1분기 월평균 : 1,2,3월의 총범죄수 평균) **

Hide code cell source
df['총범죄수'] = df['절도']  +df['사기']  +df['배임']  +df['방화']  +df['폭행']
df['분기'] = [x+'_'+str(y) for x in ['2018','2019'] for y in range(1,5) for z in range(3)]

max_ = df.groupby(['분기'])['총범죄수'].mean().sort_values().index[-1] # '2019_02'
result = df[df.분기 ==max_].사기.max()
print(result)
27766

작업 2유형#

Attention

건강 상태 분류문제 : https://www.kaggle.com/datasets/alphiree/cardiovascular-diseases-risk-prediction-dataset train = https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/ep6_p2_train.csv test = https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/ep6_p2_test.csv

예측 변수 General_Health, test.csv에 대해 ID별로 General_Health 값을 예측하여 제출, 제출 데이터 컬럼은 ID와 General_Health 두개만 존재해야함. 평가지표는 f1score

import pandas as pd
train = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/ep6_p2_train.csv')
test = pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/krdatacertificate/ep6_p2_test.csv')

display(train.head(2))
test.head(2)
ID General_Health Checkup Exercise Heart_Disease Skin_Cancer Other_Cancer Depression Diabetes Arthritis Sex Age_Category Height_(cm) Weight_(kg) BMI Smoking_History Alcohol_Consumption Fruit_Consumption Green_Vegetables_Consumption FriedPotato_Consumption
0 ID_1473 Good Within the past 2 years Yes No No No No No Yes Female 55-59 168.0 77.11 27.44 No 1.0 12.0 4.0 4.0
1 ID_2045 Good Within the past 2 years Yes No No No No No No Female 40-44 152.0 58.97 25.39 No 0.0 8.0 16.0 8.0
ID Checkup Exercise Heart_Disease Skin_Cancer Other_Cancer Depression Diabetes Arthritis Sex Age_Category Height_(cm) Weight_(kg) BMI Smoking_History Alcohol_Consumption Fruit_Consumption Green_Vegetables_Consumption FriedPotato_Consumption
0 ID_14547 Within the past year Yes No No No No No No Male 35-39 180.0 81.65 25.10 No 15.0 8.0 25.0 12.0
1 ID_26 5 or more years ago No No Yes No No No No Male 60-64 183.0 79.38 23.73 No 1.0 4.0 4.0 4.0
Hide code cell source
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score
from sklearn.ensemble import RandomForestClassifier
import numpy as np
y = train['General_Health']
x = train.drop(columns =['General_Health','ID'])
test_x = test.drop(columns =['ID'])


dum_x = pd.get_dummies(x)


# train에는 있고, test에는 없는 데이터 존재 컬럼숫자가 다름 -> reindex해줘야함
dum_test = pd.get_dummies(test_x)
dum_test = dum_test.reindex(columns = dum_x.columns, fill_value=0)



x_train,x_test,y_train,y_test = train_test_split(dum_x,y)


rr = RandomForestClassifier()
rr.fit(x_train,y_train)


pred = rr.predict(x_test)
print('test f1score', f1_score(y_test,pred,average='macro'))


pred_test = rr.predict(dum_test)

sumission = pd.DataFrame()
sumission['ID'] = test['ID']
sumission['price']  = pred_test
sumission.head()
# sumission.to_csv('00000000.csv',index=Fasle)
test f1score 0.5461326334144193
ID price
0 ID_14547 Excellent
1 ID_26 Excellent
2 ID_14103 Good
3 ID_10946 Excellent
4 ID_1572 Excellent

작업 3유형#

Attention

A 도시의 남성 600명과 여성 550명이 있다. 남성들 중 흡연자 비율은 0.2이며 여성들 중 흡연자 비율은 0.26이다.
남성과 여성 간에 흡연 여부에 따른 인구 비율이 다른지 확인하고 싶다. 유의 수준 0.05하 귀무가설에 대해 기각 / 채택 여부와 p-value값을 각각 출력하라

Hide code cell source
import numpy as np
from scipy.stats import chi2_contingency

# 남성과 여성의 인구 수
total_male = 600
total_female = 550

# 남성과 여성 중 흡연자의 비율
smoking_ratio_male = 0.2
smoking_ratio_female = 0.26

# 흡연자와 비흡연자의 인구 수 계산
smoking_male = int(total_male * smoking_ratio_male)
non_smoking_male = int(total_male - smoking_male)

smoking_female = total_female * smoking_ratio_female
non_smoking_female = total_female - smoking_female

# 데이터 배열 생성 (빈도로 변환)
data = np.array([[smoking_male, non_smoking_male], [smoking_female, non_smoking_female]])

# 카이제곱 검정 수행
chi2_stat, p_val, dof, expected = chi2_contingency(data)

print('기각',p_val)
기각 0.018786854975740768

Attention

연령 몸무게 콜레스테롤 수치 데이터 데이터 출처 : https://www.kaggle.com/datasets/hangawqadir/erbil-heart-disease-dataset 데이터 url : https://raw.githubusercontent.com/Datamanim/datarepo/main/adp/28/p7.csv

연령, 몸무게,콜레스테롤 수치 데이터

import pandas as pd 
df= pd.read_csv('https://raw.githubusercontent.com/Datamanim/datarepo/main/adp/28/p7.csv')
df.head()
age Cholesterol weight
0 65 69.0 111.0
1 54 117.0 81.0
2 61 86.2 72.0
3 57 76.0 78.0
4 62 160.0 61.0

3-2-a

age와 Cholesterol을 가지고 weight를 예측하는 선형 회귀 모델을 만들려고한다. age의 회귀 계수를 구하여라

Hide code cell source
import statsmodels.api as sm
X = sm.add_constant(df[['age', 'Cholesterol']]) 
model = sm.OLS(df['weight'], X)
results = model.fit()

# 전체 회귀 결과 출력
# print(results.summary())

print(results.params['age'])
-0.036101669143864965

3-1-b

age가 고정일 때 Cholesterol와 weight가 선형관계에 있다는 가설을 유의수준 0.05하에 검정하라

Hide code cell source
H = results.pvalues['Cholesterol']

if H <0.05 : 
    print('선형 관계에 있다.')
    
else:
    print('선형 관계에 없다.')
선형 관계에 있다.

3-1-b

age가 55, Cholesterol가 72.6일때 위 모델을 기반으로 weight값을 예측하라.

Hide code cell source
pred = results.predict([1,55,72.6]) # const , age,Cholesterol
print(pred[0])
78.85771011344593