【问题标题】:Interpolating curve with dates on the x-axis用 x 轴上的日期插值曲线
【发布时间】:2016-12-20 00:45:52
【问题描述】:

我已经绘制了一条曲线,其中 x 轴只是使用 datetime 模块的日期,但我希望能够在它们之间进行插值。例如,我想在 2017-05-05 上插入值,即使我没有在那里输入值。我的代码如下:

import pandas as pd
import numpy as np
import datetime as dt
import matplotlib.pyplot as plt


eudata = pd.read_csv("H:/euriborspots.csv")

months = eudata.ix[:, 'Expiry']
badspots = eudata.ix[:, 'Spot'] 
spots = [100 -x for x in badspots]


dates = [dt.datetime.strptime(d,'%Y-%m-%d').date() for d in months]
datearray = np.array(dates)
ratearray = np.array(spots)

ratecurve = plt.plot(datearray, ratearray)

有人可以帮忙吗?

【问题讨论】:

  • 什么样的插播?线性(绘制“最佳拟合”线)、多项式、指数,使用机器学习技术?有些比其他的更容易做到:)

标签: python matplotlib interpolation


【解决方案1】:

插值是一个相当广泛的话题。像往常一样,Wikipedia 是一个从兔子洞开始的好地方,如果您有兴趣的话,尽管首选的方法往往是特定领域的。在 python 中,您的选项可能会按照我考虑的顺序列出:

1.通用轮询

Python 在scipy package 中支持多种技术

例如,从文档中,可以使用 1D interpollat​​ion 来执行

scipy.interpolate.interp1d(x, y, kind='linear'))

插入一维函数。

x 和 y 是用于逼近某个函数 f 的值数组:y = f(x)。该类返回一个函数,其调用方法使用插值来查找新点的值。

从这里开始的好处是它是一个快速简单的启动位置,需要最少的依赖项(例如包含在 Anaconda 中),并且如果您希望以后更改模型,它提供了很大的灵活性。

Plotting code found in the docs:in the docs

2。简单的一维插值

简单的一维插值也可以找到right in numpy

numpy.interp(x, xp, fp, )

一维线性插值。

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

从这里开始的好处是,如果您使用 matplotlib,您可能已经设置了 numpy

3.更复杂的插值

引用的 Scipy 包含所有典型用例,但有时您需要一个具有更高通用性的模型。 Sklearn 包含许多强大的回归技术。例如,Gaussian Process 允许插值包括除值之外的方差估计。来自文档:


处理日期

如果您担心无法将日期轻松输入到大多数这些数值方法中,有几种existing (python using datetimes) (an example of conversion in matlab forums) 方法可以做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2020-09-03
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多