So, for a forecasting project, I have a really long Dataframe of multiple time series of the following type (it has a numerical index):
| date | time_series_id | value |
|---|---|---|
| 2015-08-01 | 0 | 0 |
| 2015-08-02 | 0 | 1 |
| 2015-08-03 | 0 | 2 |
| 2015-08-04 | 0 | 3 |
| 2015-08-01 | 1 | 2 |
| 2015-08-02 | 1 | 3 |
| 2015-08-03 | 1 | 4 |
| 2015-08-04 | 1 | 5 |
My objective, is to add 3 new columns to these dataset, for each individual time series (each id) that correspond to trend, seasonal and resid.
According to the characteristics of the dataset, they tend to have Nans at the start and the end of the dates.
What I was trying to do was the following:
from statsmodels.tsa.seasonal import seasonal_decompose
df.assign(trend = lambda x: x.groupby("time_series_id")["value"].transform(lambda s: s.mask(~s.isna(), other= seasonal_decompose(s[~s.isna()], model='aditive', extrapolate_trend='freq').trend))
The expected output (trend value are not actual values) should be:
| date | time_series_id | value | trend |
|---|---|---|---|
| 2015-08-01 | 0 | 0 | 1 |
| 2015-08-02 | 0 | 1 | 1 |
| 2015-08-03 | 0 | 2 | 1 |
| 2015-08-04 | 0 | 3 | 1 |
| 2015-08-01 | 1 | 2 | 1 |
| 2015-08-02 | 1 | 3 | 1 |
| 2015-08-03 | 1 | 4 | 1 |
| 2015-08-04 | 1 | 5 | 1 |
But I get the following error message:
AttributeError: 'Int64Index' object has no attribute 'inferred_freq'
In a previous iteration of my code, this worked for my individual time series data frames, since I had embedded the date column as an index of the data frame instead of an additional column, so the "x" that the lambda function takes has already a "date time" index appropriate for the seasonal_decompose function.
df.assign(
trend = lambda x: x["value"].mask(~x["value"].isna(), other =
seasonal_decompose(x["value"][~x["value"].isna()], model='aditive', extrapolate_trend='freq').trend))
My questions are, first: is it possible to achieve this using groupby? Or other approaches are possible second: is it possible to handle this that doesn't eat much memory? The original dataset I'm working on has approximately 1MM ~ rows, so any help is really welcomed :).
