はじめに
ここでは例えとして年始1/1から何日が経ったか算出する
sklearnのライブラリの一つであるLabelEncoderのfitとtransformを使う
方法
まずはライブラリのインポートと、ラベルエンコーダーのオブジェクトの生成
import pandas as pd import numpy as np import matplotlib.pyplot as plt %matplotlib inline from sklearn.preprocessing import LabelEncoder # doy = Day of Year le_doy_raw = LabelEncoder() le_doy_raw.fit(pd.date_range('2018-01-01', '2018-12-31', freq='1 D'))
Output:
LabelEncoder()
date_rangeを使うとdatetime形式で格納される
le_doy_raw.classes_[:5]
Output:
array(['2018-01-01T00:00:00.000000000', '2018-01-02T00:00:00.000000000',
'2018-01-03T00:00:00.000000000', '2018-01-04T00:00:00.000000000',
'2018-01-05T00:00:00.000000000'], dtype='datetime64[ns]')
今回は月日の情報さえ取れれば良いので、mapでラベルを変換する
le_doy = LabelEncoder() le_doy.fit(pd.date_range('2018-01-01', '2018-12-31', freq='1 D').map(lambda x: x.strftime('%m-%d'))) le_doy.classes_[:5]
Outrput:
array(['01-01', '01-02', '01-03', '01-04', '01-05'], dtype=object)
サンプルとして2/1から3/31までの1週間ごとの日付を格納したDataFrameを作成
df = pd.DataFrame({'date':pd.date_range('2017-02-01', '2017-3-31', freq='1 W').map(lambda x: x.strftime('%m-%d'))}) df
date | |
---|---|
0 | 02-05 |
1 | 02-12 |
2 | 02-19 |
3 | 02-26 |
4 | 03-05 |
5 | 03-12 |
6 | 03-19 |
7 | 03-26 |
transformメソッドを使って上で作成したデータセットの日付が1/1から数えて何日経ったかを算出できる
df["dayofyear"] = le_doy.transform(df.date)
df
date | dayofyear | |
---|---|---|
0 | 02-05 | 35 |
1 | 02-12 | 42 |
2 | 02-19 | 49 |
3 | 02-26 | 56 |
4 | 03-05 | 63 |
5 | 03-12 | 70 |
6 | 03-19 | 77 |
7 | 03-26 | 84 |
これで例えば2/5は1/1から数えて35日目ということがわかる
機械学習のモデルの特徴量として経過日数を取り込む時に重宝する