使用 2 列在 pandas 中插入股票数据

Interpolate stock data in pandas using 2 columns

我想做股票行情的插值。我缺少一天的数据(如示例):

import numpy as np
import pandas as pd
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(
    {'opening': [0.5, 1.3, np.NaN, 4, 5, 1],
     'closing': [0, 1, np.NaN, 2, 10, 2]}, index=dates)

            opening  closing
2013-01-01      0.5      0.0
2013-01-02      1.3      1.0
2013-01-03      NaN      NaN
2013-01-04      4.0      2.0
2013-01-05      5.0     10.0
2013-01-06      1.0      2.0

我需要方法来有效地插入 NaN,2013-01-02closing2013-01-03opening2013-01-04opening2013-01-03 中的 closing。期望的输出:

2013-01-01      0.5      0.0
2013-01-02      1.3      1.0
2013-01-03      1.0      4.0
2013-01-04      4.0      2.0
2013-01-05      5.0     10.0
2013-01-06      1.0      2.0

我试图使用应用程序,但它只有关于当前行的信息。我需要访问上一行和下一行。

使用DataFrame.assign,因为有必要通过正向或反向填充替换缺失值'paralel':

df = df.assign(opening = df['opening'].fillna(df['closing'].ffill()),
               closing = df['closing'].fillna(df['opening'].bfill()))
print (df)
            opening  closing
2013-01-01      0.5      0.0
2013-01-02      1.3      1.0
2013-01-03      1.0      4.0
2013-01-04      4.0      2.0
2013-01-05      5.0     10.0
2013-01-06      1.0      2.0