Python与NaN的线性回归

2024-06-16 13:18:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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并对剩余值进行线性回归?

提前多谢了。

-全球价值


Tags: timestats线性nanthisslope全球work
1条回答
网友
1楼 · 发布于 2024-06-16 13:18:49

是的,您可以使用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

相关问题 更多 >