【问题标题】:Index and Date Problem on Plot Prediction情节预测的索引和日期问题
【发布时间】:2021-10-23 13:51:39
【问题描述】:

我有一个数据框:

import yfinance as yf
df = yf.download('AAPL',
                 start='2001-01-01',
                 end='2005-12-31',
                 progress=False)

然后我将其分成比例为 80:20 的训练测试集。这是一些检查我的训练集和测试集索引的代码。

train_df.index

输出是

test_df.index

输出是

从训练数据中得到模型后,我用252个测试数据做预测,结果是

如何将预测输出更改为具有 datetime %Y%m%d 索引而不是整数索引的数据帧?我已经阅读了这个stackoverflow中的很多文章和答案,但我还没有找到解决方案。

【问题讨论】:

    标签: python dataframe datetime indexing prediction


    【解决方案1】:

    您可以做的一件事是在模型训练/推理之前简单地保存日期​​时间索引,然后将其重新加入 RangeIndex。

    即:

    time_index = df.reset_index()[['utc']] #replace utc with your index name
    df = df.reset_index()
    

    训练模型,然后加入 RangeIndex。然后将 index 设置回 DatetimeIndex。

    prediction = prediction.join(time_index)
    prediction.set_index('utc', inplace=True)
    

    工作示例:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame({'col1':np.arange(10)}, index=pd.date_range('2021-01-01', '2021-01-10'))
    df.index.name = 'Date'
    #Save the time_index but indexed by RangeIndex to allow for join after prediction
    time_index = df.reset_index()[['Date']]
    
    #Some arbitrary prediction dataframe with a RangeIndex
    prediction = pd.DataFrame({'predictions':np.arange(0,10)})
    
    #joins prediction and time_index on the RangeIndex
    prediction = prediction.join(time_index)
    
    #Sets index to the time_index
    prediction.set_index('Date', inplace=True)
    

    您现在将拥有一个如下所示的数据框:

                predictions
    Date
    2021-01-01            0
    2021-01-02            1
    2021-01-03            2
    2021-01-04            3
    2021-01-05            4
    2021-01-06            5
    2021-01-07            6
    2021-01-08            7
    2021-01-09            8
    2021-01-10            9
    

    只是为了驱动这个家,这里是一个使用您的数据源的具体示例:

    import yfinance as yf
    import pandas as pd
    import numpy as np
    from sklearn.linear_model import LinearRegression
    from sklearn.model_selection import train_test_split
    
    df = yf.download('AAPL',
                     start='2001-01-01',
                     end='2005-12-31',
                     progress=False)
    
    #Save the time_index but indexed by RangeIndex to allow for join after prediction
    time_index = df.reset_index()[['Date']]
    df = df.reset_index()
    
    #Assuming we predict Volume
    y = df[['Volume']]
    X = df.drop(columns=['Volume', 'Date'])
    
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
    
    model = LinearRegression()
    model.fit(X_train, y_train)
    
    #Predict values, transpose to fit into dataframe
    predicted_values = model.predict(X_test).T[0]
    
    #Create prediction dataframe
    prediction = pd.DataFrame({'y-pred':predicted_values}, index=X_test.index)
    
    #join test or true data to prediction for comparison
    prediction = prediction.join(y_test)
    
    #joins prediction and time_index on the RangeIndex
    prediction = prediction.join(time_index)
    
    #Sets index to the time_index
    prediction.set_index('Date', inplace=True)
    

    导致:

    
                      y-pred      Volume
    Date
    2001-07-26  3.893012e+08   369140800
    2004-12-20  1.191681e+09  1168126400
    2005-02-17  8.905975e+08  1518473600
    2002-12-03  2.004725e+08   227869600
    2005-10-10  8.430103e+08   50750560
    

    【讨论】:

    • 显示错误:ValueError: 'Date'既是索引级别又是列标签,不明确。
    • @Wind 听起来您已经将日期作为预测数据框中的一列?如果是这样,您可以简单地使用 .set_index-command 将其设置为索引。你能提供predictions.columns吗?
    • 对不起,错误已更改为 ValueError:列重叠但未指定后缀:Index(['Date'], dtype='object')。顺便说一句,你的意思是 time_axis 是之前描述过的 time_index 吗?
    • @Wind 我已经用一个工作示例更新了我的答案,以更清楚地说明我的意思。是的,time_axis 是我的 type-O,我的意思是 time_index。
    • @Wind 这不会影响这项技术。对于每个 RangeIndex (即 integer ),都有一个相应的日期。我拼凑了一个简单的脚本来驱动要点。希望它可以解决问题。如果您希望索引有序,则必须对结果预测数据框进行 sort_index。
    猜你喜欢
    • 2020-06-16
    • 2017-04-16
    • 2018-07-31
    • 2020-03-04
    • 2022-06-11
    • 2021-03-19
    • 1970-01-01
    • 2019-09-29
    • 2019-09-18
    相关资源
    最近更新 更多