Decomposing trend, seasonal and residual time series elements
Works fine when you convert your index
to DateTimeIndex
:
df.reset_index(inplace=True)df['Date'] = pd.to_datetime(df['Date'])df = df.set_index('Date')s=sm.tsa.seasonal_decompose(df.divida)<statsmodels.tsa.seasonal.DecomposeResult object at 0x110ec3710>
Access the components via:
s.resids.seasonals.trend
Statsmodel will decompose the series only if you provide frequency. Usually all time series index will contain frequency eg: Daywise, Business days, weekly So it shows error. You can remove this error by two ways:
- What Stefan did is he gave the index column to pandas
DateTime
function. It uses internal functioninfer_freq
to find the frequency and return the index with frequency. - Else you can set the frequency to your index column as
df.index.asfreq(freq='m')
. Herem
represents month. You can set the frequency if you have domain knowledge or byd
.
It depends on the index format. You can have DateTimeIndex or you can have PeriodIndex. Stefan presented the example for DateTimeIndex. Here is my example for PeriodIndex. My original DataFrame has a MultiIndex index with year in first level and month in second level. Here is how I convert it to PeriodIndex:
df["date"] = pd.PeriodIndex (df.index.map(lambda x: "{0}{1:02d}".format(*x)),freq="M")df = df.set_index("date")
Now it is ready to be used by seasonal_decompose.