This article is available in:
English
この記事は日付、時間の間隔が空いているデータに対して、データの間隔を埋める方法の備忘録です。
日時の間隔を埋めるには、pandasのasfreq
関数を使います。
この記事のコードは以下のgoogle colabで試すことができます。

Google Colab
pythonコード
例として次のようなデータを扱います(以下、df
という変数にデータが格納されているとします)。
10分単位のデータですが、ところどころにデータが存在しない、時間の間隔が空いているデータとなっています。

データを埋める方針としては、
- 時刻のカラム(datetime)をindexに指定
- pandasの
asfreq
関数を使用 - indexを元に戻す
の手順を踏みます。
import pandas as pd
df_ = df.set_index('datetime') # datetimeをindexに指定
df_ = df_.asfreq(freq='10min')
df_fill = df_.reset_index() # indexを元に戻す
print(df_fill)

以上のように間が空いてしまった日時データを埋めることができます。
なお、asfreq
関数のfreq
に指定できる引数は下記の公式リファレンスに詳しく載っています。
Time series / date functionality — pandas 2.2.3 documentation