pandas PeriodIndex:freq not specified and cannot be inferred from first element

記事公開日:
最終更新日:

This post is also available in: English-US (英語)

pandasにて時系列データを扱っている際に、下記のようなエラーに遭遇したので、備忘録的にメモを書いています。

ValueError freq not specified and cannot be inferred from first element

解決法はエラーの内容通り、freq を明確に指定する必要があるみたいです。
なので、DatetimeIndex から PeriodIndex にpandasのデータフレームを変換するサンプルコードを掲載しています。

・[14行目]DatetimeIndex のサンプルデータフレームを作成
・[37行目] DatetimeIndex を PeriodIndex に変換

import pandas as pd
from datetime import datetime, timedelta

# 日付のリストを生成
date_list = [datetime(2021,1,1) + timedelta(days=i) for i in range(100)]
print(date_list)
"""
#output
[datetime.datetime(2021, 1, 1, 0, 0), datetime.datetime(2021, 1, 2, 0, 0),...]
"""

#データフレーム生成
#date_listから、データフレームのindexとcolumnsムを生成
df_date = pd.DataFrame(date_list, columns=['Date'], index=date_list)
print(df_date)
"""
#output
                 Date
2021-01-01 2021-01-01
2021-01-02 2021-01-02
2021-01-03 2021-01-03
2021-01-04 2021-01-04
2021-01-05 2021-01-05
...               ...
2021-04-06 2021-04-06
2021-04-07 2021-04-07
2021-04-08 2021-04-08
2021-04-09 2021-04-09
2021-04-10 2021-04-10
"""

print(type(df_date.index)) #<class 'pandas.core.indexes.datetimes.DatetimeIndex'>
print(type(df_date["Date"][0])) #<class 'pandas._libs.tslibs.timestamps.Timestamp'>

#PeriodIndexに変換
#freq="B"は、月曜から金曜日の意
df_date.index = df_date.index.to_period(freq="B")
df_date["Date"] = df_date["Date"].dt.to_period(freq="B")
print(df_date)
"""
#output

                  Date
2021-01-01  2021-01-01
2021-01-04  2021-01-04
2021-01-04  2021-01-04
2021-01-04  2021-01-04
2021-01-05  2021-01-05
...                ...
2021-04-06  2021-04-06
2021-04-07  2021-04-07
2021-04-08  2021-04-08
2021-04-09  2021-04-09
2021-04-12  2021-04-12
"""

print(type(df_date.index)) #<class 'pandas.core.indexes.period.PeriodIndex'>
print(type(df_date["Date"][0])) #<class 'pandas._libs.tslibs.period.Period'>

About
Amelt.net,LLCの創業者で、費用対効果の高い統合webマーケティングによりビジネスパートナーとして継続的にサポート。詳しいより。ブログの更新情報TwitterLinkedIn、またRSSfeedlyにてお知らせしていますのでフォローよろしくお願い致します。