R(或 Python)函数用于时间序列插值


有哪些

用于时间序列插值的R(或Python(函数?

线性插值的基本示例:

Day  x       --->    Day  x
1    4               1    4
2    NA              2    3
3    2               3    2
4    NA              4    4
5    NA              5    6
6    8               6    8

是否有与移动平均线或类似函数插值的函数?

谢谢。

在 R 中,来自插补包的 na.interpolation 函数可以使用线性、样条或 Stineman 方法进行插值。假设您的数据框称为 dat ,下面是一个进行线性插值的示例,这是na.interpolation函数的默认设置。

# Load package
library(imputeTS)
# View dat
dat
#   Day  x
# 1   1  4
# 2   2 NA
# 3   3  2
# 4   4 NA
# 5   5 NA
# 6   6  8
# Linear interpolation
dat$x <- na.interpolation(dat$x)
# View dat again
dat
#   Day x
# 1   1 4
# 2   2 3
# 3   3 2
# 4   4 4
# 5   5 6
# 6   6 8

如果要使用样条斯蒂内曼插值方法,请将option参数更改为 splinestine

至于移动平均线,我们可以使用 zoo 包中的rollapply函数。下面是一个显示窗口宽度为 3 的移动平均线的示例。

# Load package
library(zoo)
# View dat
dat
#   Day  x
# 1   1  4
# 2   2 NA
# 3   3  2
# 4   4 NA
# 5   5 NA
# 6   6  8
# Create a new column with moving average with window = 3
dat$y <- rollapply(dat$x, width = 3, FUN = function(x) mean(x, na.rm = TRUE),
                   fill = NA, align = "center")
# View dat again
dat
#   Day  x  y
# 1   1  4 NA
# 2   2 NA  3
# 3   3  2  2
# 4   4 NA  2
# 5   5 NA  8
# 6   6  8 NA
# Filling NA in x based on y
dat$x <- ifelse(is.na(dat$x), dat$y, dat$x)
# Remove y
dat$y <- NULL
# View dat again
# dat
#   Day x
# 1   1 4
# 2   2 3
# 3   3 2
# 4   4 2
# 5   5 8
# 6   6 8

数据

dat <- read.table(text = "Day  x
1    4
                  2    NA
                  3    2
                  4    NA
                  5    NA
                  6    8",
                  header = TRUE, stringsAsFactors = FALSE)

R中,另一个选项是从zoo na.approx

library(zoo)
df1$x <- na.approx(df1$x)
df1$x
#[1] 4 3 2 4 6 8

在 numpy 中,有用于简单插值 numpy.interp((

如果 x 有 nan-值,我会使用代码,例如:

xnan = numpy.isnan(x)  
x_interpolated = numpy.interp(Day, Day[~xnan], x[~xnan])

在你的第二组数字中,天是 1、2、2、...也许它们应该与第一组相同。

听如何(有效(移动平均线会很有趣,有一些功能吗?

最新更新