AttributeError: 'RangeIndex' object has no attribute 'inferred_freq'

Viewed 8705

I'm trying to do forecast in my python 3.x. So I wrote following code

from statsmodels.tsa.seasonal import seasonal_decompose
decomposition = seasonal_decompose(ts_log)

trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid

But I'm getting error message

AttributeError: 'RangeIndex' object has no attribute 'inferred_freq'

Can you please help me to resolve the issue

2 Answers

You need to make sure that your Panda Series object ts_log have a DateTime index with inferred frequency.

For example:

ts_log.index
>>> DatetimeIndex(['2014-01-01', ... '2017-12-31'],
              dtype='datetime64[ns]', name='Date', length=1461, freq='D')

Noticed how there's a an attribute freq='D', it means that Pandas infer that the Pandas Series is indexed Daily (D=Daily).

Now to achieve this, I assume your Series have a column call 'Date'. And here's the code to do it:

# Convert your daily column from just string to DateTime (skip if already done)
ts_log['Date'] = pd.to_datetime(ts_log['Date'])
# Set the column 'Date' as index (skip if already done)
ts_log = ts_log.set_index('Date')
# Specify datetime frequency
ts_log = ts_log.asfreq('D')

For frequency other than Daily, refer here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html#offset-aliases

For statsmodel==0.10.1 and where ts_log is not a dataframe or a dataframe without datetime index, use the following

decomposition = seasonal_decompose(ts_log, freq=1)
Related