此代码在 python 中的作用是什么?
What this code does in python?
我正在学习 python 并且想知道下面的代码在 Python 中做了什么:
def inter_lin_nan(ts, rule):
ts = ts.resample(rule)
mask = np.isnan(ts)
ts[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), ts[~mask])
return(ts)
我知道这是一个对时间序列数据进行插值的函数,第二行根据规则(例如1hr)对数据进行重新采样。第四行和第五行呢?这个插值是如何完成的? np.interp
需要什么值,~mask
是什么?
这在文档中有准确描述:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html
numpy.interp(x, xp, fp, left=None, right=None, period=None)[source]
One-dimensional linear interpolation.
Returns the one-dimensional piecewise linear interpolant to a function
with given values at discrete data-points.
所以行 ts[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), ts[~mask])
简单地将已知值插入 NaN
s(在上一行中标识,并且它们的索引在 mask
中编码)。
pandas.Series.resample 允许您获取时间序列并根据规则以不同的频率对其进行采样。假设您有一系列 49 天的观测值,并且您想要一系列 7 周均值 return。它会为您执行此操作,然后您将使用 numpy.interp 来估算返回为 nan 的任何值。
我正在学习 python 并且想知道下面的代码在 Python 中做了什么:
def inter_lin_nan(ts, rule):
ts = ts.resample(rule)
mask = np.isnan(ts)
ts[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), ts[~mask])
return(ts)
我知道这是一个对时间序列数据进行插值的函数,第二行根据规则(例如1hr)对数据进行重新采样。第四行和第五行呢?这个插值是如何完成的? np.interp
需要什么值,~mask
是什么?
这在文档中有准确描述:
http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html
numpy.interp(x, xp, fp, left=None, right=None, period=None)[source] One-dimensional linear interpolation.
Returns the one-dimensional piecewise linear interpolant to a function with given values at discrete data-points.
所以行 ts[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), ts[~mask])
简单地将已知值插入 NaN
s(在上一行中标识,并且它们的索引在 mask
中编码)。
pandas.Series.resample 允许您获取时间序列并根据规则以不同的频率对其进行采样。假设您有一系列 49 天的观测值,并且您想要一系列 7 周均值 return。它会为您执行此操作,然后您将使用 numpy.interp 来估算返回为 nan 的任何值。