데이터 : 전력거래소 시간대별 수요량 데이터, 연료원별 거래량 데이터 활용 기간 : 2021년

In [1]:
import numpy as np
import pandas as pd
from datetime import datetime, date
import datetime

import matplotlib.pyplot as plt
import seaborn as sns
In [2]:
plt.rcParams['figure.figsize'] = (14, 9)
plt.rcParams['font.family'] = 'Malgun Gothic'
plt.rcParams['font.size'] = 12
plt.rcParams['axes.unicode_minus']
Out[2]:
True
In [3]:
# (2021년) 에너지원별 누적 그래프
def energy_type_stack():
    data = pd.read_excel('연료원별 전력거래량_2021.xlsx')
    # [행 : 거래시간, 열 : 연료원]으로 변환
    table = pd.pivot_table(data, values='전력거래량(MWh)', index='거래시간', columns='연료원')

    temp_col = ['원자력', '유연탄', 'LNG', '무연탄', 'IGCC',  'LPG', '가스압', '경유', '기타', '매립가스',  '바이오가스',
     '바이오매스', '바이오중유', '부생가스', '소수력', '수력', '양수', '연료전지',   '중유', '태양광', '폐기물', '풍력', '해양에너지']
    table = table[temp_col] # 거래량 비중이 높은 에너지원별로 재정렬 (상위 : 원전, 유언탄, LNG까지만)

    table.plot(kind='area', stacked=True) # 누적 그래프
    plt.grid()
    plt.ylabel('평균 전력거래량(MWh)')
    plt.title('시간대별 에너지원별 평균 전력거래량(MWh)')
    plt.show()
In [4]:
energy_type_stack()
In [5]:
df = pd.read_excel('시간별 전력수요량_2013_2021.xlsx', index_col=[0], parse_dates=True)
df
Out[5]:
1시 2시 3시 4시 5시 6시 7시 8시 9시 10시 ... 15시 16시 17시 18시 19시 20시 21시 22시 23시 24시
날짜
2013-01-01 60178 57862 56165 55135 54450 54401 54147 52467 50469 49572 ... 49213 49357 50362 53115 55205 55437 55348 55790 58195 59330
2013-01-02 57067 55148 53983 53571 54027 55388 57753 60781 66494 70869 ... 72228 71945 72641 73387 72294 69989 67893 66504 67435 69275
2013-01-03 66263 64233 63194 62461 62649 63396 65098 67745 72982 75999 ... 75576 75168 75791 75922 75469 73118 70769 68726 69593 71346
2013-01-04 68403 66143 65051 64245 64152 64678 66494 68851 73835 76175 ... 74977 74275 74909 75344 74504 71957 69715 68155 68948 70834
2013-01-05 68053 65801 64439 63437 63135 63250 63658 63441 65640 66806 ... 64767 63613 63095 63230 64253 63353 62455 62314 64350 66687
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
2021-12-27 66465 64473 63140 62540 63122 65025 69117 76487 86054 87590 ... 88435 89654 90708 88653 85067 81527 78245 74696 73048 74217
2021-12-28 71059 68940 67701 67076 67184 68598 72033 78270 86809 88717 ... 87226 87627 88077 85978 83052 80011 77035 73589 71856 72875
2021-12-29 69651 67276 65941 65136 65534 66910 70309 75972 84106 85966 ... 82446 82500 83608 82009 79711 77646 75511 72342 70829 71882
2021-12-30 68581 66406 65155 64639 65121 66804 70225 75906 83494 83012 ... 81928 83044 84564 82901 80604 78216 76176 73142 71610 72472
2021-12-31 69373 67187 65955 65431 65798 67226 70163 75036 81748 81729 ... 73706 74401 75972 75798 74578 72976 71602 69383 68874 70123

3287 rows × 24 columns

In [6]:
# (2021년) 시간대별 전력피크 횟수 계산
def count_peak_month_2021(data):
    data = data['2021'] # 2021년만 선택
    data = data.idxmax(axis=1) # 하루 중 최고값을 기록한 시간을 추출
    data = data.to_frame()
    data['month'] = data.index.month
    data.columns = ['peak_hour', 'month']
    #print(data)

    total = pd.DataFrame(index=data.columns)

    for idx in data['month'].unique():
        month = data[data['month'] == idx] # 월별 데이터

        peak_hour = month['peak_hour'].value_counts() # 'peak' 컬럼에 있는 값별 count
        peak_hour = pd.DataFrame(peak_hour)

        total = pd.concat([total, peak_hour], axis=1) # 월별로 계속 결합

    total.columns = data['month'].unique() # 전체 월을 컬럼으로 변경
    total = total.fillna(0) # 피크가 기록되지 않은 시간대의 Nan 값을 0으로 변경
    total = total.T.drop(['month', 'peak_hour'], axis=1) # 행/열 전환
    total = total.stack().reset_index() # 열('시간')을 행으로 전환하고, idnex를 reset
    total.columns = ['month', 'hour', 'count'] # 컬럼명 변경

    sns.barplot(data=total, x='month', y='count', hue='hour') # 멀티 막대 그래프 그리기

    plt.grid()
    plt.ylabel('시간대별 전력피크 횟수')
    plt.title('2021년 월별/시간대별 전력피크 횟수')
    plt.show()
In [7]:
count_peak_month_2021(df.copy())
In [8]:
# (2021년) 부하율 그래프 그리는 함수(일반 라인, 월별 4분위)
def load_factor(data):
    data = data['2021'].copy() # 2021년 데이터만 추출
    data['LF'] = data.mean(axis=1) / data.max(axis=1) * 100 # 일별 부하율 산정

    data['LF'].plot() # 부하율 라인그래프 그리기
    plt.grid()
    plt.ylabel('부하율(%)')
    plt.title('2021년도 일별 부하율(%)')
    plt.show()

    data['month'] = data.index.month
    data4 = data[['LF', 'month']]
    #print(data4.head())

    data4.boxplot(column='LF', by='month') # 월별로 부하율을 4분위 그래프 그리기
    plt.ylabel('부하율(%)')
    plt.title('부하율(%) 4분위 그래프')
    plt.show()
In [9]:
load_factor(df.copy())
In [10]:
# (2021년) 연간 시간대별, 요일별, 주별 그래프 그리기
def EDA_2021(data):
    data = data['2021'].copy()  # 2021년 데이터만 추출
    stack_df = data.stack()

    stack_df = stack_df.reset_index()
    stack_df.columns = ['date', 'hour', 'pcon']
    stack_df['dayofweek'] = stack_df['date'].dt.dayofweek
    stack_df['weekofyear'] = stack_df['date'].dt.weekofyear
    #print(stack_df)

    sns.pairplot(stack_df, x_vars=['hour'], y_vars='pcon', hue='hour', height=5, plot_kws={'alpha':0.1, 'linewidth':0})
    plt.ylabel('전력소비량(MWh)')
    plt.suptitle('연간 시간대별 전력소비량(MWh) 분포')
    plt.grid()
    plt.show()

    sns.pairplot(stack_df, x_vars=['dayofweek'], y_vars='pcon', hue='hour', height=5, plot_kws={'alpha': 0.1, 'linewidth': 0})
    plt.ylabel('전력소비량(MWh)')
    plt.suptitle('연간 요일별/시간대별 전력소비량(MWh) 분포(월, 화, 수, 목, 금, 토, 일)')
    plt.grid()
    plt.show()

    sns.pairplot(stack_df, x_vars=['weekofyear'], y_vars='pcon', hue='hour', height=5, plot_kws={'alpha': 0.1, 'linewidth': 0})
    plt.ylabel('전력소비량(MWh)')
    plt.suptitle('연간 주별/시간대별 전력소비량(MWh) 분포')
    plt.grid()
    plt.show()
In [11]:
EDA_2021(df.copy())
In [12]:
# (2021년) 일, 월 전력소비량
def simple_EDA_2021(data):
    df_day = data['2021'].copy() # 2021년 데이터 추출
    df_day['sum'] = df_day.sum(axis=1) # 일별 전력소비량 합계 구함

    df_day['sum'].plot()
    plt.grid()
    plt.ylabel('전력소비량(MWh)')
    plt.title('2021년 일별 전력소비량(MWh)')
    plt.show()

    df_month = data['2021'].copy() # 2021년 데이터 추출
    df_month['sum'] = df_month.sum(axis=1) # 일별 전력소비량 합계 구함
    df_month['month'] = df_month.index.month
    grp_month = df_month.groupby('month')['sum'].sum()/1000 # 월별 전력소비량 합계 구함

    grp_month.plot(kind='bar')
    plt.grid()
    plt.ylabel('전력소비량(GWh)')
    plt.title('2021년 월별 전력소비량(GWh)')
    plt.show()
In [14]:
simple_EDA_2021(df.copy())