此建议适用于任何类型的索引值(字符串、日期或整数),只要它们是唯一的。
简答:
创建最长系列的熊猫数据框。该数据框将有一个索引。从该系列中获取最后 50 个索引值,并将其与新数据框中的预测值相关联。您的两个数据框将具有不同的长度,因此您必须将它们 merge 放在一起才能获得两个相等长度的系列。使用这种方法,您的前 100 个预测值将为空,但您的数据将具有关联的索引,以便您可以根据 test1 系列绘制它。
详情:
由于您没有共享可重现的数据集,因此我制作了一些应与您的数据集结构匹配的随机数据。下面的第一个 sn-p 将重现您的情况,并使两个数组 test1 和 **predictions1 ** 可用于建议的解决方案。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(123456)
rows = 150
df = pd.DataFrame(np.random.randint(-4,5,size=(rows, 1)), columns=['test1'])
datelist = pd.date_range(pd.datetime(2017, 1, 1).strftime('%Y-%m-%d'), periods=rows).tolist()
df['dates'] = datelist
df = df.set_index(['dates'])
df.index = pd.to_datetime(df.index)
df['test1'] = df['test1'].cumsum()
# Get the last 50 values of test1 (as array instead of dataframe)
# to mimic the names and data types of your source data
test1 = df['test1'].values
predicionts1 = df['test1'].tail(50).values
predictions1 = predicionts1*1.1
# Reproducing your situation:
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
plt.plot(test1)
plt.plot(predictions1, color = 'red')
plt.show()
下面的sn-p会在test1上叠加predictions1:
# Make a new dataframe of your prediction values
df_new = pd.DataFrame(test1)
df_new.columns = ['test1']
# Retrieve index values
new_index = df_new['test1'].tail(len(predictions1)).index
# Make a dataframe with your prediction values and your index
new_series = pd.DataFrame(index = new_index, data = predictions1)
# Merge the dataframes
df_new = pd.merge(df_new, new_series, how = 'left', left_index=True, right_index=True)
df_new.columns = ['test1', 'predictions1']
# And plot it
import matplotlib.pyplot as plt
plt.figure(figsize=(15,8))
plt.plot(df_new['test1'])
plt.plot(df_new['predictions1'], color = 'red')
plt.show()