【发布时间】:2021-06-28 20:57:28
【问题描述】:
所以,对于一个预测项目,我有一个非常长的 Dataframe,其中包含以下类型的多个时间序列(它有一个数字索引):
| 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 |
我的目标是为这些数据集添加 3 个新列,分别对应于 trend、seasonal 和 resid 的每个单独的时间序列(每个 id)。
根据数据集的特点,他们倾向于在日期的开头和结尾都有Nans。
我试图做的是:
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))
预期输出(趋势值不是实际值)应该是:
| 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 |
但我收到以下错误消息:
AttributeError: 'Int64Index' object has no attribute 'inferred_freq'
在我的代码的上一次迭代中,这适用于我的个人时间序列数据帧,因为我已将 date 列嵌入为数据帧的索引而不是附加列,因此“x”表示lambda 函数需要一个适合seasonal_decompose 函数的“日期时间”索引。
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))
我的问题是,首先:是否可以使用 groupby 来实现这一点?或者第二个可能的其他方法:是否可以处理不占用太多内存的问题?我正在处理的原始数据集大约有 1MM ~ 行,因此非常欢迎任何帮助:)。
【问题讨论】:
标签: python pandas time-series pandas-groupby statsmodels