用NaN进行Python线性回归

时间:2016-07-05 17:41:14

标签: python linear-regression

values=([0,2,1,'NaN',6],[4,4,7,6,7],[9,7,8,9,10])
time=[0,1,2,3,4]
slope_1 = stats.linregress(time,values[1]) # This works
slope_0 = stats.linregress(time,values[0]) # This doesn't work

有没有办法忽略NaN并对剩余值进行线性回归?

提前多多感谢。

-GV

1 个答案:

答案 0 :(得分:3)

是的,您可以使用statsmodels执行此操作:

import statsmodels.api as sm
from numpy import NaN

x = [0, 2, NaN, 4, 5, 6, 7, 8]
y = [1, 3, 4,   5, 6, 7, 8, 9]

model = sm.OLS(y, x, missing='drop')
results = model.fit()

In [2]: results.params
Out[2]: array([ 1.16494845])

这样可以获得与删除缺少数据的行相同的结果:

x = [0, 2, 4, 5, 6, 7, 8]
y = [1, 3, 5, 6, 7, 8, 9]

model = sm.OLS(y, x)
results = model.fit()

In [4]: results.params
Out[4]: array([ 1.16494845])

但是会自动处理它。如果需要,您还可以传递drop以外的参数:http://statsmodels.sourceforge.net/devel/generated/statsmodels.regression.linear_model.OLS.html