python - 在 Python 中使用时间序列分解中的运行中位数提取趋势?
问题描述
我有许多不同的时间序列,它们是季节性的,包括大的异常值。
当使用运行平均值来提取趋势时(如在 STL 实现中),它可能会破坏提取的趋势和季节性成分,并在残差中引入错误的异常值。
解决这个问题的一种方法是使用移动中位数来提取趋势,是否有任何 python 包类似于 R 中的十进制(https://rdrr.io/cran/pastecs/man/decmedian.html)?
另一种解决方案可能是尝试将以下代码片段翻译为 Python,但我不确定如何翻译该xts
部分。
decompose.median <- function(m, period) {
trend <- rollapply(m, width = period, fill = NA, align = "center",
FUN = median, na.rm = TRUE)
season <- m - trend
figure <- numeric(period)
l <- length(m)
index <- seq.int(1, l, by = period) - 1
for (i in 1:period) figure[i] <- median(season[index + i], na.rm = TRUE)
seasonal=xts(rep(figure, l %/% period + 1)[seq_len(l)], order.by = index(m))
list(observed = m,
trend = trend,
seasonal = seasonal,
remainder = m - trend - seasonal)
}
蟒蛇尝试
def decompose_median(df,col,period):
m = df[col]
trend = df[col].rolling(period).median()
season = m - trend
figure = np.zeros(period)
l = len(m)
index = np.array(range(1,100,10)) - 1
for i in range(1,period):
figure[i] = np.median(season.dropna()[index + i])
#### Not sure how to translate this part
seasonal=xts(rep(figure, l %/% period + 1)[seq_len(l)], order.by =
index(m))
list(observed = m,
trend = trend,
seasonal = seasonal,
remainder = m - trend - seasonal)
}
解决方案
推荐阅读
- android - Recyclerview 不显示卡片视图
- mysql - 如何在数据库中搜索k个最近的元素?
- oracle - 在没有别名或表名的查询列中找不到 ODAC 字段“column_name”
- python - 从嵌套字典中的 N 个列表中选择值
- jquery - 按下一个按钮时,有多个按钮和一个 div 对应的 div 将显示
- node.js - 如何在 Nodejs 中设置 Azure CosmosDB 触发器
- html - 类的字体很棒:fas fa-user 给包一个矩形而不是加号 (+)
- python - 为什么 pytorch DataLoader 在 numpy 数组和列表上的行为不同?
- arrays - 如何从数据网格和数组中删除行
- javascript - Vue:在挂载中执行异步请求