頻度変更:リサンプリング

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 # 既定: 年末四半期
Pythonでの時系列データ操作

アップサンプリング:四半期⇒月

monthly = quarterly.asfreq('M') # 月末頻度へ
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') # 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での時系列データ操作

Passons à la pratique !

Pythonでの時系列データ操作

Preparing Video For Download...