시계열 빈도 변환: 리샘플링

Python으로 시계열 데이터 다루기

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

빈도 변환: 리샘플링

  • DateTimeIndex: .asfreq()로 빈도 설정 및 변경
  • 빈도 변환은 데이터에 영향을 줍니다
    • 업샘플링: 누락 데이터를 채우거나 보간
    • 다운샘플링: 기존 데이터를 집계
  • pandas API:
    • .asfreq(), .reindex()
    • .resample() + 변환 메서드
Python으로 시계열 데이터 다루기

시작하기: 분기별 데이터

dates = pd.date_range(start='2016', periods=4, freq='Q')

data = range(1, 5)
quarterly = pd.Series(data=data, index=dates)
quarterly
2016-03-31    1
2016-06-30    2
2016-09-30    3
2016-12-31    4
Freq: Q-DEC, dtype: int64 # Default: year-end quarters
Python으로 시계열 데이터 다루기

업샘플링: 분기 => 월

monthly = quarterly.asfreq('M') # to month-end frequency
2016-03-31    1.0
2016-04-30    NaN
2016-05-31    NaN
2016-06-30    2.0
2016-07-31    NaN
2016-08-31    NaN
2016-09-30    3.0
2016-10-31    NaN
2016-11-30    NaN
2016-12-31    4.0
Freq: M, dtype: float64
  • 업샘플링 시 결측값이 생성됩니다
monthly = monthly.to_frame('baseline') # to DataFrame
Python으로 시계열 데이터 다루기

업샘플링: 채우기 방법

monthly['ffill'] = quarterly.asfreq('M', method='ffill')

monthly['bfill'] = quarterly.asfreq('M', method='bfill')
monthly['value'] = quarterly.asfreq('M', fill_value=0)
Python으로 시계열 데이터 다루기

업샘플링: 채우기 방법

  • bfill: 역방향 채우기
  • ffill: 전방향 채우기
            baseline  ffill  bfill  value
2016-03-31       1.0      1      1      1
2016-04-30       NaN      1      2      0
2016-05-31       NaN      1      2      0
2016-06-30       2.0      2      2      2
2016-07-31       NaN      2      3      0
2016-08-31       NaN      2      3      0
2016-09-30       3.0      3      3      3
2016-10-31       NaN      3      4      0
2016-11-30       NaN      3      4      0
2016-12-31       4.0      4      4      4
Python으로 시계열 데이터 다루기

누락 월 추가: .reindex()

dates = pd.date_range(start='2016', 
                      periods=12, 
                      freq='M')
DatetimeIndex(['2016-01-31', 
               '2016-02-29', 
               ..., 
               '2016-11-30', 
               '2016-12-31'],
        dtype='datetime64[ns]', freq='M')
  • .reindex():
    • DataFrame을 새 인덱스에 맞게 재구성
    • .asfreq()와 동일한 채우기 방식 적용
quarterly.reindex(dates)
2016-01-31    NaN
2016-02-29    NaN
2016-03-31    1.0
2016-04-30    NaN
2016-05-31    NaN
2016-06-30    2.0
2016-07-31    NaN
2016-08-31    NaN
2016-09-30    3.0
2016-10-31    NaN
2016-11-30    NaN
2016-12-31    4.0
Python으로 시계열 데이터 다루기

연습해 봅시다!

Python으로 시계열 데이터 다루기

Preparing Video For Download...