Search code examples
pythonstatsmodels

Seasonal decompose 'You must specify a period or x must be a pandas object with a PeriodIndex or a DatetimeIndex with a freq not set to None'


I am trying to use statsmodels.tsa's seasonal decompose, but I keep getting this error

'ValueError: You must specify a period or x must be a pandas object with a PeriodIndex or a DatetimeIndex with a freq not set to None'

I have tryed to use a DatetimeIndex with a monthly period like this time.index =time.index.to_timestamp(freq='M') but still the error persists.

My code is below

import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
from pandas.plotting import register_matplotlib_converters

time = pd.DataFrame({'Date':['2022-03-01','2022-03-02','2022-03-03','2022-03-04','2022-03-05',
                   '2022-03-06','2022-03-07','2022-03-08','2022-03-09','2022-03-10',
                   '2022-03-11','2022-03-12','2022-03-13','2022-03-14','2022-03-15'],
                   'Employment_Rate':[52,12,18,35,75,95,85,45,75,85,95,65,85,75,78]
                   })

# Convert 'Date' to datetime and set as index
time['Date'] = pd.to_datetime(time['Date'], format='%Y-%m-%d')
time['Date'] = time['Date'].dt.to_period('M')

time.set_index('Date', inplace=True)

# Sort index and drop NA values
time.sort_index(inplace=True)
time.dropna(inplace=True)

# Convert PeriodDtype index to DatetimeIndex 
time.index = time.index.to_timestamp(freq='M')

# Graphing
register_matplotlib_converters()
plt.rc("figure", figsize=(16, 12))
plt.rc("font", size=13)

decomposition = seasonal_decompose(time['Employment_Rate'])

Solution

  • I ran your code and found that the index is 2022-03-31 for each row. I was able to get it to work by removing these two lines:

    • time['Date'] = time['Date'].dt.to_period('M')
    • time.index = time.index.to_timestamp(freq='M')