将新行添加到现有数据框/系列

时间:2017-12-21 09:55:52

标签: python time-series arima

我的数据集的最后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

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

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

1 个答案:

答案 0 :(得分:0)

您可以从附加列表中创建新的DataFrame,然后将其与现有列表合并。我认为最简单的是,如果您将数据作为字典列表提供,也包含日期索引。即类似的东西(我假设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)

当然,date中使用的predictions密钥需要与原始数据框中使用的密钥类型相同。生成的df_concatenated将两个数据帧放在一起。要绘制结果,您只需调用df_concatenated.plot()(或调用您需要的相应绘图功能)。

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