#!/usr/bin/env python # coding: utf-8 # ## 데이터 불러오기 및 전처리 # ### 데이터의 형태 파악 # In[1]: # https://datalab.visitkorea.or.kr/datalab/portal/tst/getEntcnyFrgnCustForm.do # 목적별/국적별에서 2010~2021년의 데이터 다운로드 import pandas as pd kto_2021 = pd.read_csv('방한 외래관광객_20211112.csv', header=1, skipfooter=4) kto_2021.head() # In[2]: kto_2021.tail() # ### 데이터 전처리 하기 # In[3]: # 증감률 필드 삭제 및 필드명 수정 # 인원수 -> 총인원수 # 인원수.1 -> 관광 # 인원수.2 -> 상용 # 인원수.3 -> 공용 # 인원수.4 -> 유학연수 # 인원수.5 -> 기타 kto_2021.columns # In[4]: kto_2021.drop(['증감률(%)', '증감률(%).1', '증감률(%).2', '증감률(%).3', '증감률(%).4', '증감률(%).5'], axis='columns', inplace=True) kto_2021.rename(columns = {'인원수': '총인원수', '인원수.1': '관광', '인원수.2': '상용', '인원수.3': '공용', '인원수.4': '유학연수', '인원수.5': '기타'}, inplace = True) kto_2021.head() # In[5]: # 필드 형태 확인 kto_2021.info() # In[6]: # object to int kto_2021.replace(',','', regex=True, inplace=True) kto_2021['총인원수'] = pd.to_numeric(kto_2021['총인원수']) kto_2021['관광'] = pd.to_numeric(kto_2021['관광']) kto_2021['상용'] = pd.to_numeric(kto_2021['상용']) kto_2021['공용'] = pd.to_numeric(kto_2021['공용']) kto_2021['유학연수'] = pd.to_numeric(kto_2021['유학연수']) kto_2021['기타'] = pd.to_numeric(kto_2021['기타']) kto_2021.info() # In[7]: kto_2021.describe() # In[8]: # 기준년월 컬럼 생성하기 kto_2021['기준년월'] = kto_2021['연도'] + kto_2021['월'] kto_2021.head() # In[9]: # unique() kto_2021['국적'].unique() # In[10]: kto_2021['대륙'].unique() # In[11]: # '소계'가 들어간 row 삭제 kto_2021['대륙'] = kto_2021['대륙'].astype('str') searchfor = ['소계', '기타', 'nan'] kto_2021 = kto_2021[~kto_2021.대륙.str.contains('|'.join(searchfor))] kto_2021.head() # In[12]: # 연도월-나라별 총인원수 관광객비율(%) 컬럼 생성하기 kto_2021['관광객비율(%)'] = \ round(kto_2021['관광'] / kto_2021['총인원수'] * 100, 1) kto_2021.head() # In[13]: # 관광객비율(%) 컬럼으로 내림차순 정렬 kto_2021.sort_values(by='관광객비율(%)', ascending=False).head() # In[14]: # 관광객비율(%) 컬럼으로 오름차순 정렬하기 kto_2021.sort_values(by='관광객비율(%)', ascending=True).head() # In[15]: # pivot_table() 함수 활용하기 kto_2021.pivot_table(values = '관광객비율(%)', index = '대륙', aggfunc = 'mean') # In[16]: # 중국 국적만 필터링하기 condition = (kto_2021.국적 == '중국') kto_2021[condition] # In[17]: # 10년동안 우리나라 방문하는 전체 외국인 관광객 숫자 구하기 tourist_sum = sum(kto_2021['관광']) tourist_sum # In[18]: # 전체비율(%) 컬럼 생성하기 kto_2021['전체비율(%)'] = \ round(kto_2021['관광'] / tourist_sum * 100, 1) kto_2021.head() # In[19]: # 전체비율(%) 컬럼 기준으로 내림차순 정렬하기 kto_2021.sort_values('전체비율(%)', ascending=False).head() # In[20]: import matplotlib.pyplot as plt # In[21]: # 중국 국적 데이터 필터링하기 condition = (kto_2021['국적'] == '중국') df_filter = kto_2021[condition] df_filter.head() # In[22]: # 시계열 그래프 그리기 1 plt.plot(df_filter['기준년월'], df_filter['관광']) plt.show() # In[23]: ## 그래프 크기 조절 plt.figure(figsize = (12, 4)) plt.rcParams["font.family"] = 'NanumGothic' ## 그래프 내용 설정 plt.plot(df_filter['기준년월'], df_filter['관광']) ## 그래프 타이틀, X축, Y축 이름 달기 plt.title('중국 국적의 관광객 추이') plt.xlabel('기준년월') plt.ylabel('관광객수') ## x 축 눈금 값 설정 plt.xticks(['201001', '201101', '201201', '201301', '201401', '201501', '201601', '201701', '201801', '201901', '202001', '202101']) ## 그래프 표현하기 plt.show() # In[24]: # 10년 관광객 수 상위 5개 kto_2021.groupby('국적')['관광'].max().sort_values(ascending=False).head(5) # In[25]: plt.figure(figsize = (20, 8)) plt.rcParams["font.family"] = 'NanumGothic' country1 = kto_2021[kto_2021['국적'] == '중국'] country2 = kto_2021[kto_2021['국적'] == '일본'] country3 = kto_2021[kto_2021['국적'] == '대만'] country4 = kto_2021[kto_2021['국적'] == '미국'] country5 = kto_2021[kto_2021['국적'] == '홍콩'] plt.plot(country1['기준년월'], country1['관광'], label='중국') plt.plot(country2['기준년월'], country2['관광'], label='일본') plt.plot(country3['기준년월'], country3['관광'], label='대만') plt.plot(country4['기준년월'], country4['관광'], label='미국') plt.plot(country5['기준년월'], country5['관광'], label='홍콩') plt.legend(loc='best', ncol=2) plt.xticks(['201001', '201101', '201201', '201301', '201401', '201501', '201601', '201701', '201801', '201901', '202001', '202101']) plt.show() # ### 히트맵 그래프 그리기 # In[26]: df_pivot = df_filter.pivot_table(values = '관광' , index = '연도' , columns = '월') df_pivot # In[27]: import matplotlib.pyplot as plt import seaborn as sns # In[28]: # 예제 3-50 히트맵 그리프 그리기 ## 그래프 크기 설정 plt.figure(figsize = (16, 10)) plt.rcParams["font.family"] = 'NanumGothic' ## 히트맵 그래프 그리기 sns.heatmap(df_pivot, annot = True, fmt = '.0f', cmap = 'rocket_r') ## 그래프 타이틀 달기 plt.title('중국 관광객 히트맵') ## 그래프 표현 plt.show() # In[ ]: # In[ ]: