【问题标题】:What this code does in python?这段代码在 python 中做了什么?
【发布时间】:2016-02-17 15:25:56
【问题描述】:

我正在学习 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)

我知道这是一个对时间序列数据进行插值的函数,第二行根据规则(例如 1 小时)重新采样数据。第四行和第五行呢?这种插值是如何完成的? np.interp 需要什么价值,~mask 是什么?

【问题讨论】:

标签: python numpy interpolation nan


【解决方案1】:

这在文档中有准确描述:

http://docs.scipy.org/doc/numpy/reference/generated/numpy.interp.html

numpy.interp(x, xp, fp, left=None, right=None, period=None)[来源] 一维线性插值。

将一维分段线性插值返回给函数 在离散数据点具有给定值

所以ts[mask] = np.interp(np.flatnonzero(mask), np.flatnonzero(~mask), ts[~mask]) 行只是将已知值插入到NaNs(在前一行中标识,并且它们的索引在mask 中编码)。

【讨论】:

    【解决方案2】:

    pandas.Series.resample 允许您获取时间序列并根据规则以不同频率对其进行采样。假设您有一系列 49 次每日观察,并且您想要一系列 7 周均值作为回报。它为您执行此操作,然后您使用 numpy.interp 来估算任何返回为 nan 的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多