【问题标题】:Add new rows to an existing dataframe/series向现有数据框/系列添加新行
【发布时间】:2017-12-21 09:55:52
【问题描述】:

我的数据集的最后 4 条记录如下所示:

date    Outbound

11/26/2017 21:00    175.5846438
11/26/2017 22:00    181.1182961
11/26/2017 23:00    112.011672
11/27/2017 00:00    43.99501014

我已经完成了样本外预测,并预测了接下来的 7 个输出,即 11 月 27 日 01:00、02:00 等。 我的预测是这样的列表形式:[100, 120, 130....]

如何将预测与日期一起添加到我的数据框或系列中,因为我需要绘制数据..

【问题讨论】:

    标签: python time-series arima


    【解决方案1】:

    您可以从附加列表中创建一个新的 DataFrame,然后将其与现有列表合并。我认为最简单的方法是,如果您将数据作为还包含日期索引的字典列表提供。 IE。类似的东西(我假设df_original 是具有原始值的数据框):

    import datetime
    import pandas
    
    # Calculating your predictions (this should be replaced with an 
    # appropriate algorithm that matches your case)
    
    latest_entry = df_original.iloc[-1]
    latest_datetime = latest_entry['date']
    
    # We assume lastest_datetime is a Python datetime object.
    # The loop below will create 10 predictions. This should be adjusted to make
    # sense for your program. I'm assuming the function `compute_prediction()`
    # will generate the predicted value. Again, this you probably want to tweak
    # to make it work in your program :) 
    # The computed predictions will be stored inside a list of dicts.
    
    predictions = list()
    
    for _ in range(10):
        predicted_date = latest_datetime + datetime.timedelta(hours=1)
        predicted_value = compute_prediction()
    
        tmp_dict = {
            'date': predicted_date, 'Outbound': predicted_value
        }
        predictions.append(tmp_dict)
    
    # Convert the list of dictionaries into a data frame.
    df_predictions = pandas.DataFrame.from_dict(predictions)
    
    # Append the values of your new data frame to the original one.
    df_concatenated = pandas.concat(df_original, df_predictions)
    

    当然,predictions 中使用的 date 键需要与原始数据框中使用的类型相同。生成的df_concatenated 将同时包含两个数据帧。要绘制结果,您只需调用df_concatenated.plot()(或调用您需要的适当绘图函数)。

    您可以找到更多关于合并多个数据框here 的详细信息。

    【讨论】:

    • 感谢您的输入,但是如果我们不知道最后一个日期值怎么办,例如:最后一个日期值是 11/27/2017 00:00,通过查看它,您准备好了字典很好,我不想有硬编码的值,如果最后一个值是别的东西,例如:11/27/2017 10:00,我希望你明白我的意思.. 如何采取最后一个值,然后增加 1 小时...
    • 嗨,我已经调整了答案,所以它现在获取最新条目,然后每隔 1 小时从那里开始生成预测。当然,上面的代码需要一些调整才能使其在您的上下文中工作(例如,您计算预测的方式)。
    • 如果这个回答有帮助,请采纳。 stackoverflow.com/help/someone-answers
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2018-10-09
    • 2018-09-03
    • 2019-12-29
    相关资源
    最近更新 更多