`.resample()`でのアップサンプリングと補間

Pythonでの時系列データ操作

Stefan Jansen

Founder & Lead Data Scientist at Applied Artificial Intelligence

頻度変換と変換メソッド

  • .resample().groupby()に類似

  • リサンプリング期間内でグループ化し、各グループにメソッドを適用

  • 新しい日付はオフセットで決定(開始・終了など)

  • アップサンプリング: 既存値の充填または補間

  • ダウンサンプリング: 既存データを集約

Pythonでの時系列データ操作

準備: 月次失業率

unrate = pd.read_csv('unrate.csv', parse_dates['Date'], index_col='Date')

unrate.info()
DatetimeIndex: 208 entries, 2000-01-01 to 2017-04-01
Data columns (total 1 columns):
UNRATE    208 non-null float64 # 頻度情報なし
dtypes: float64(1)
unrate.head()
            UNRATE
DATE
2000-01-01     4.0
2000-02-01     4.1
2000-03-01     4.0
2000-04-01     3.8
2000-05-01     4.0
  • 公表日: 月初(1日)
Pythonでの時系列データ操作

リサンプリング期間と頻度オフセット

  • resampleは頻度オフセットに合わせて新しい日付を作成
  • 暦月末以外にも複数の選択肢あり

 

Frequency Alias Sample Date
Calendar Month End M 2017-04-30
Calendar Month Start MS 2017-04-01
Business Month End BM 2017-04-28
Business Month Start BMS 2017-04-03
Pythonでの時系列データ操作

リサンプリングのロジック

リサンプリングのロジック

Pythonでの時系列データ操作

リサンプリングのロジック

リサンプリングのロジック

Pythonでの時系列データ操作

`.resample()`で頻度を付与

unrate.asfreq('MS').info()
DatetimeIndex: 208 entries, 2000-01-01 to 2017-04-01
Freq: MS
Data columns (total 1 columns):
UNRATE    208 non-null float64
dtypes: float64(1)
unrate.resample('MS') # Resampler オブジェクトを作成
DatetimeIndexResampler [freq=<MonthBegin>, axis=0, closed=left, 
                        label=left, convention=start, base=0]
Pythonでの時系列データ操作

`.resample()`で頻度を付与

unrate.asfreq('MS').equals(unrate.resample('MS').asfreq())
True
  • .resample(): ほかのメソッドを呼ぶときだけデータを返す
Pythonでの時系列データ操作

四半期実質GDP成長率

gdp = pd.read_csv('gdp.csv')

gdp.info()
DatetimeIndex: 69 entries, 2000-01-01 to 2017-01-01
Data columns (total 1 columns):
gpd    69 non-null float64 # 頻度情報なし
dtypes: float64(1)
gdp.head(2)
            gpd
DATE
2000-01-01  1.2
2000-04-01  7.8
Pythonでの時系列データ操作

月次の実質GDP成長率を補間

gdp_1 = gdp.resample('MS').ffill().add_suffix('_ffill')
       gpd_ffill
DATE
2000-01-01  1.2
2000-02-01  1.2
2000-03-01  1.2
2000-04-01  7.8
Pythonでの時系列データ操作

月次の実質GDP成長率を補間

gdp_2 = gdp.resample('MS').interpolate().add_suffix('_inter')
            gpd_inter
DATE
2000-01-01  1.200000
2000-02-01  3.400000
2000-03-01  5.600000
2000-04-01  7.800000
  • .interpolate(): 既存点間を直線で補間
Pythonでの時系列データ操作

2つのDataFrameの連結

df1 = pd.DataFrame([1, 2, 3], columns=['df1'])

df2 = pd.DataFrame([4, 5, 6], columns=['df2'])
pd.concat([df1, df2])
   df1  df2
0  1.0  NaN
1  2.0  NaN
2  3.0  NaN
0  NaN  4.0
1  NaN  5.0
2  NaN  6.0
Pythonでの時系列データ操作

2つのDataFrameの連結

pd.concat([df1, df2], axis=1)
   df1  df2
0    1    4
1    2    5
2    3    6
  • axis=1: 横方向に連結
Pythonでの時系列データ操作

補間した実質GDP成長率を可視化

pd.concat([gdp_1, gdp_2], axis=1).loc['2015':].plot()

補間した実質GDP成長率のプロット

Pythonでの時系列データ操作

GDP成長率と失業率を結合

pd.concat([unrate, gdp_inter], axis=1).plot();

GDP成長率と失業率の組み合わせ

Pythonでの時系列データ操作

演習に進みましょう

Pythonでの時系列データ操作

Preparing Video For Download...