【问题标题】:Interpolation of sparse time-related (datetimes) entries稀疏时间相关(日期时间)条目的插值
【发布时间】:2019-08-20 13:20:41
【问题描述】:

我正在尝试通过时间插入数据。我在某些日期生成了稀疏的数据点(我可以使用下面的代码绘制),并且我正在尝试绘制一条连续的插值路径或穿过数据的脊椎。

我尝试使用 scipy.interpolate 中的 interp1d,但如果因为我使用日期而失败.. 如何绘制插值路径?

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
from scipy.interpolate import interp1d

history = ['22.4 25/07/2019','22.8 26/07/2019','23.5 27/07/2019','27.7 28/07/2019','22.4 29/07/2019','25 01/08/2019','18.22 02/08/2019','32.5 03/08/2019','28 04/08/2019','28.2 07/08/2019','31 08/08/2019','24.99 09/08/2019','24.8 10/08/2019','25.1 13/08/2019','24.0 14/08/2019','29.4 16/08/2019','28.6 19/08/2019','27 21/08/2019','26.3 22/08/2019','25.7 23/08/2019','23.9 27/08/2019','26.3 30/08/2019','28.4 01/09/2019']

def someMathGoesHere(w):
    #...
    return float(w)

def parseHistory(hist):
    dates = []
    vals  = []
    for i in hist:
        i = i.split(" ")
        val = i[0]
        day = datetime.datetime.strptime(i[1], '%d/%m/%Y')
        vals.append(val)
        dates.append(day)
    return [vals,dates]

def plot(data):
    [v,d] = parseHistory(data)
    vv = [someMathGoesHere(i) for i in v]

    fig,ax = plt.subplots(figsize = (13.3,7.5),constrained_layout=True)
    ax.set(title="test")
    ax.plot(d,vv,'ro',markeredgecolor=(0,0,0,1,),markersize=5,markerfacecolor='blue')
    ax.axhspan(15,20,facecolor='#e15a1b',alpha=0.2)
    ax.axhspan(20,28,facecolor='#11d7b0',alpha=0.2)
    ax.axhspan(28,50,facecolor='#e050eb',alpha=0.2)

    plt.ylim(15,32)

    month_interval = 1
    ax.get_xaxis().set_major_locator(mdates.MonthLocator(interval=month_interval))
    ax.get_xaxis().set_major_formatter(mdates.DateFormatter("%b %Y"))
    ax.margins(y=0.1)
    plt.setp(ax.get_xticklabels(),rotation=30,ha="right")
    plt.show()
    return True

plot(history)

谢谢!

【问题讨论】:

    标签: python date matplotlib interpolation spline


    【解决方案1】:

    是的..明白了!

    import pandas as pd
    from scipy.interpolate import interp1d
    
    history = ['80 25/07/2019','80.1 26/07/2019','78.5 27/07/2019','77 28/07/2019','76.4 29/07/2019','75.9 01/08/2019','77.1 02/08/2019','76 03/08/2019','75.3 04/08/2019','74.8 07/08/2019','74.5 08/08/2019','74 09/08/2019','74.8 10/08/2019','75.1 13/08/2019','74.0 14/08/2019','73.4 16/08/2019','72.6 19/08/2019','73. 21/08/2019','72 22/08/2019','71.7 23/08/2019','71.3 27/08/2019','70.1 30/08/2019','70 01/09/2019']
    
    def convert_dates_to_days(dates, start_date=None, name='Day'):
        if start_date:
            ts0 = pd.Timestamp(start_date).timestamp()
        else:
            ts0 = 0
        return ((dates.apply(pd.Timestamp.timestamp) - 
                ts0)/(24*3600)).rename(name)
    
    [v,d] = parseHistory(history)
    data = pd.DataFrame(list(zip(d[0:22],v[0:22])),columns = ['Date','Value'])
    print len(history)
    
    
    startDay = data.Date.iloc[0].strftime('%d/%m/%Y')
    endDay = data.Date.iloc[-1].strftime('%d/%m/%Y')
    
    x = convert_dates_to_days(data.Date, start_date=startDay)
    y = data.Value
    f2 = interp1d(x, y, kind='cubic',fill_value='extrapolate')
    
    all_dates = pd.Series(pd.date_range(startDay, endDay))
    x_all = convert_dates_to_days(all_dates, start_date=startDay)
    
    data.set_index('Date')['Value'].plot(style='o')
    plt.plot(all_dates, f2(x_all), '-')
    plt.grid()
    
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 2013-12-25
      • 1970-01-01
      • 1970-01-01
      • 2016-01-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多