在熊猫数据框中添加行移位

时间:2020-04-16 07:31:12

标签: python pandas time-series

我有一个熊猫df,我是通过使用shift()函数迭代原始df来创建的:

for i in range(2, 4):
    df["lag_{}".format(i)] = df.x.shift(i)

因此,将有实际的x列和lag2-lag10列,它们具有偏移的x值。我已经为回归模型训练了该数据集,以进行单步向前预测。希望在数据帧的末尾添加新行,其中x的值为nan,并且从最后位置开始偏移值,以便能够使用这些新的滞后来拟合模型以预测此新的nan值。如何在熊猫中做到这一点?谢谢!

已更新: 有用于df的图片,即未加粗化的df(粗体)-所需的行:

enter image description here

1 个答案:

答案 0 :(得分:1)

DataFrame.append与带有键x的字典一起使用:

df = pd.DataFrame({'x':range(10)})

df1 = df.append({'x':np.nan}, ignore_index=True)
#alternative
#df1 = df.append(pd.Series([np.nan], index=['x']), ignore_index=True)

for i in range(2, 10):
    df1["lag_{}".format(i)] = df1.x.shift(i)
print (df1)
      x  lag_2  lag_3  lag_4  lag_5  lag_6  lag_7  lag_8  lag_9
0   0.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
1   1.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN    NaN
2   2.0    0.0    NaN    NaN    NaN    NaN    NaN    NaN    NaN
3   3.0    1.0    0.0    NaN    NaN    NaN    NaN    NaN    NaN
4   4.0    2.0    1.0    0.0    NaN    NaN    NaN    NaN    NaN
5   5.0    3.0    2.0    1.0    0.0    NaN    NaN    NaN    NaN
6   6.0    4.0    3.0    2.0    1.0    0.0    NaN    NaN    NaN
7   7.0    5.0    4.0    3.0    2.0    1.0    0.0    NaN    NaN
8   8.0    6.0    5.0    4.0    3.0    2.0    1.0    0.0    NaN
9   9.0    7.0    6.0    5.0    4.0    3.0    2.0    1.0    0.0
10  NaN    8.0    7.0    6.0    5.0    4.0    3.0    2.0    1.0