Pythonのpandasのdate_range()で時系列データを生成
期間を指定
開始と終了を指定して、時系列データを生成できます。
デフォルトでは日単位で生成されます。
import pandas as pd
print(pd.date_range('2018-11-04', '2018-11-08'))
開始と期間を指定
periodsに単位を指定できます。例えば、下記は3日間の期間で生成されます。
print(pd.date_range('2018-11-04', periods=3))
年単位で生成
freq='Y'を設定することで年単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='Y'))
月末単位で生成
freq='M'を設定することで月末単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='M'))
週単位で生成
freq='W'を設定することで週単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='W'))
日単位で生成
freq='D'を設定することで日単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='D'))
時間単位で生成
freq='H'を設定することで時間単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='H'))
分単位で生成
freq='min'を設定することで分単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='min'))
秒単位で生成
freq='S'を設定することで秒単位で生成できます
print(pd.date_range('2018-11-04', periods=3, freq='S'))
スポンサーリンク
サンプルコード
下記がサンプルコードになります。
$ cat sample.py
#!/usr/bin/env python3
# coding: UTF-8
import pandas as pd
print("開始と終了を指定")
print(pd.date_range('2018-11-04', '2018-11-08'))
print("開始と期間を指定")
print(pd.date_range('2018-11-04', periods=3))
print("年単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='Y'))
print("月末単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='M'))
print("週単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='W'))
print("日単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='D'))
print("時間単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='H'))
print("分単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='min'))
print("秒単位で生成")
print(pd.date_range('2018-11-04', periods=3, freq='S'))
下記が実行結果になります。
$ ./sample.py
開始と終了を指定
DatetimeIndex(['2018-11-04', '2018-11-05', '2018-11-06', '2018-11-07',
'2018-11-08'],
dtype='datetime64[ns]', freq='D')
開始と期間を指定
DatetimeIndex(['2018-11-04', '2018-11-05', '2018-11-06'], dtype='datetime64[ns]', freq='D')
年単位で生成
DatetimeIndex(['2018-12-31', '2019-12-31', '2020-12-31'], dtype='datetime64[ns]', freq='A-DEC')
月末単位で生成
DatetimeIndex(['2018-11-30', '2018-12-31', '2019-01-31'], dtype='datetime64[ns]', freq='M')
週単位で生成
DatetimeIndex(['2018-11-04', '2018-11-11', '2018-11-18'], dtype='datetime64[ns]', freq='W-SUN')
日単位で生成
DatetimeIndex(['2018-11-04', '2018-11-05', '2018-11-06'], dtype='datetime64[ns]', freq='D')
時間単位で生成
DatetimeIndex(['2018-11-04 00:00:00', '2018-11-04 01:00:00',
'2018-11-04 02:00:00'],
dtype='datetime64[ns]', freq='H')
分単位で生成
DatetimeIndex(['2018-11-04 00:00:00', '2018-11-04 00:01:00',
'2018-11-04 00:02:00'],
dtype='datetime64[ns]', freq='T')
秒単位で生成
DatetimeIndex(['2018-11-04 00:00:00', '2018-11-04 00:00:01',
'2018-11-04 00:00:02'],
dtype='datetime64[ns]', freq='S')
