데이터분석/Data Analysis With GPT

GPT와 함께 분석해본 중국 관광객의 한국 방문 현황

스윗보스 2023. 9. 25. 08:33

 

GPT와 함께, 중국 관광객의 한국 방문 현황을 분석해봤습니다.

(데이터를 수집하고 전처리하는 과정 역시, 별도로 GPT와 선행 진행했습니다.)

 

시각화를 통해 알 수 있는 사실은 중국 관광객은 8월에 주로 한국에 방문을 했다는 기록입니다.

아래 시각화를 진행하면서 가장 재밌었던 포인트는, 중요한 K드라마 반영시기, 올림픽, 사드 이슈 시기를 GPT에 물어봐서 차트에 포함한 것입니다.

그리고, 데이터를 어떻게 가져오면 좋을지 정도(SQL 구현)는 인간이 개입하는게 훨씬 더 자연스러운거 같습니다. 이 마저도 언젠가는 정복될수도 있겠지만요.

 

GPT와의 대화를 통해 어떻게 프로그램을 구현했는지 궁금하신분은 아래 채팅을 참고해주세요.

GPT와의 챗: https://chat.openai.com/share/c89f93e6-8943-4e7e-b7a2-fb62fcf4396b

 

GPT와 함께 구현한 코딩도 아래에 포함합니다.

(데이터 수집과 전처리가 별도로 필요하므로 아래 코드는 개인 환경에서는 실행되지 않습니다. 참고만해주세요.) 

import pymysql
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.family'] = 'Malgun Gothic'  # '맑은 고딕'으로 설정
plt.rcParams['axes.unicode_minus'] = False  # 마이너스 부호 문제 해결


def fetch_country_visitor_data(country_name, host, user, password, database):
    # SQL 쿼리
    query = """
    SELECT CONCAT(SUBSTR(T1.YM,1,4),'-',SUBSTR(T1.YM,5,2)) AS `년월`,
           T1.IMMI_NAT_CD AS `국가코드`,
           T1.CNT AS `방문자수`,
           T2.IMMI_NAT_NM AS `국가명`
    FROM HOMEWORKDB.IMMI_YM T1
    INNER JOIN HOMEWORKDB.IMMI_NAT T2 ON (T2.IMMI_NAT_CD = T1.IMMI_NAT_CD)
    WHERE T1.ED_CD = 'E'
    AND    T2.IMMI_NAT_NM = %s
    ORDER BY T1.YM, T1.IMMI_NAT_CD;
    """

    # 데이터베이스 연결 설정
    conn = pymysql.connect(host=host,
                           user=user,
                           password=password,
                           db=database,
                           charset='utf8')

    # pandas를 사용해 SQL 실행
    df = pd.read_sql(query, conn, params=(country_name,))

    conn.close()  # 데이터베이스 연결 종료

    return df

def plot_country_visitor_data(df):
    # 국가명과 시작월, 종료월 추출
    country_name = df['국가명'].iloc[0]
    start_month = df['년월'].iloc[0]
    end_month = df['년월'].iloc[-1]

    # 각 년도별 최대 방문객수 계산
    df['년도'] = df['년월'].str[:4]
    max_visitors_by_year = df.groupby('년도')['방문자수'].max()

    # 년도별 방문객수에 따른 색상 농도 계산
    colors = []
    for year, max_visitors in max_visitors_by_year.iteritems():
        year_data = df[df['년도'] == year]['방문자수']
        year_colors = [plt.cm.Blues(visitors/max_visitors) for visitors in year_data]
        colors.extend(year_colors)

    # 차트 설정
    plt.figure(figsize=(12, 6))
    bars = plt.bar(df['년월'], df['방문자수'], color=colors)

    # 매년 1월에 세로선 추가
    for label in df['년월']:
        if '-01' in label:
            plt.axvline(x=label, color='gray', linestyle='--', linewidth=0.8)

    # 년도별로 가장 많은 방문객이 있는 월의 Bar 위에 월을 text로 표시
    for year, max_visitors in max_visitors_by_year.iteritems():
        year_data = df[df['년도'] == year]
        max_month_row = year_data[year_data['방문자수'] == max_visitors].iloc[0]
        month = max_month_row['년월'][-2:]
        position = df['년월'].tolist().index(max_month_row['년월'])
        plt.text(position, max_month_row['방문자수'] + 1000, month, ha='center')  # 1000은 텍스트를 바로 위에 위치시키기 위한 조정값

    # x축 라벨 조절: 01월 데이터만 라벨에 표시
    x_labels = [label if '-01' in label else '' for label in df['년월']]
    plt.xticks(ticks=df['년월'], labels=x_labels, rotation=45)

    # 이벤트 및 한류 드라마 년월
    events = {
        '2017-03': '사드 문제',
        '2015-06': 'MERS',
        '2020-01': '코로나19',
        '2018-02': '평창 올림픽',
        '2014-09': '인천 아시안 게임',
        '2002-01': '겨울연가',
        '2013-12': '별에서 온 그대',
        '2016-02': '태양의 후예',
        '2016-12': '도깨비'
    }

    for event_date, event_name in events.items():
        if event_date in df['년월'].values:
            # plt.axvline(x=df[df['년월'] == event_date].index[0], color='gray', linestyle='--', alpha=0.7)
            plt.text(df[df['년월'] == event_date].index[0], df[df['년월'] == event_date]['방문자수'].values[0] + 100000,
                     event_name+"["+event_date+"]", rotation=90, verticalalignment='bottom', color='red',fontsize=9)

    plt.xlabel('년월')
    plt.ylabel('방문객')
    plt.title(f'{country_name} ({start_month}~{end_month})')
    plt.tight_layout()
    plt.show()


def show_country_stat(country):
    df = fetch_country_visitor_data(country, 'localhost', 'root', '1qaz2wsx', 'HOMEWORKDB')
    plot_country_visitor_data(df)



if __name__ == '__main__':
    show_country_stat("중국")

 

위 내용은, "GPT 강력해진 데이터분석"이란 주제로 온라인 세미나로 진행했던 내용중 일부입니다. 언제한번 무료로 세미나를 한번 더 해볼까 생각중입니다.