Sklearn或Pandas,通过简单的线性回归插补缺失值



我有数据,时间序列数据,我想插补缺失的数据。 我不能使用列的平均值,因为我认为它不适合时间序列数据。 所以我想要简单的线性回归来估算它

Day, Price
1 , NaN
2, NaN
3, 1800
4, 1900
5, NaN
6, NaN
7, 2000
8, 2200

怎么做?

我更喜欢使用熊猫来做这件事, 但是如果没有其他方法,我可以使用 sklearn :)

您可以使用interpolate执行此操作:

df['Price'].interpolate(method='linear', inplace=True)

结果:

Price   Date
0   NaN     1
1   NaN     2
2   1800.000000     3
3   1900.000000     4
4   1933.333333     5
5   1966.666667     6
6   2000.000000     7
7   2200.000000     8

如您所见,这只会向前填充缺失值。如果还想填充前两个值,请使用参数limit_direction="both"

df['Price'].interpolate(method='linear', inplace=True, limit_direction="both")

有不同的插值方法,例如二次曲线或样条曲线,有关更多信息,请参阅文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.interpolate.html

最新更新