gpt4 book ai didi

python - Pandas Dataframe 中多列的普通最小二乘回归

转载 作者:行者123 更新时间:2023-11-28 20:39:21 26 4
gpt4 key购买 nike

我正在尝试找到一种方法来迭代代码以在 Z3 以上的许多列上进行线性回归。这是名为 df1 的数据框的片段

    Time    A1      A2      A3      B1      B2      B3
1 1.00 6.64 6.82 6.79 6.70 6.95 7.02
2 2.00 6.70 6.86 6.92 NaN NaN NaN
3 3.00 NaN NaN NaN 7.07 7.27 7.40
4 4.00 7.15 7.26 7.26 7.19 NaN NaN
5 5.00 NaN NaN NaN NaN 7.40 7.51
6 5.50 7.44 7.63 7.58 7.54 NaN NaN
7 6.00 7.62 7.86 7.71 NaN NaN NaN

此代码仅返回唯一一列的线性回归的斜率系数,并将该值连接到一个名为 series 的 numpy 系列,这是提取第一列斜率的样子:

from sklearn.linear_model import LinearRegression

series = np.array([]) #blank list to append result

df2 = df1[~np.isnan(df1['A1'])] #removes NaN values for each column to apply sklearn function
df3 = df2[['Time','A1']]
npMatrix = np.matrix(df3)
X, Y = npMatrix[:,0], npMatrix[:,1]
slope = LinearRegression().fit(X,Y) # either this or the next line
m = slope.coef_[0]

series= np.concatenate((SGR_trips, m), axis = 0)

就目前而言,我正在使用这段代码,将“A1”替换为新的列名,一直到“Z3”,这是非常低效的。我知道有很多简单的方法可以用一些模块来做到这一点,但我的缺点是在时间序列中有所有这些中间 NaN 值,所以我似乎仅限于这种方法或类似的方法。

我尝试使用 for 循环,例如:

for col in df1.columns:

并替换“A1”,例如代码中的 col,但这似乎不起作用。

有什么方法可以更有效地做到这一点?

谢谢!

最佳答案

一个类轮(或三个)

time = df[['Time']]
pd.DataFrame(np.linalg.pinv(time.T.dot(time)).dot(time.T).dot(df.fillna(0)),
['Slope'], df.columns)

enter image description here

分解并进行一些解释

使用OLS的封闭形式

enter image description here

在这种情况下,Xtime,我们将 time 定义为 df[['Time']] .我使用双括号来保留数据框及其两个维度。如果我做了单括号,我会得到一个系列及其一维。那么点积就不那么漂亮了。

enter image description here

np.linalg.pinv(time.T.dot(time)).dot(time.T)

Ydf.fillna(0)。是的,我们可以一次完成一个专栏,但为什么我们可以一起完成。您必须处理 NaN。你会想象如何与他们打交道?只有在你有数据的时候才这样做吗?这相当于在 NaN 点放置零。所以,我做到了。

最后,我使用 pd.DataFrame(stuff, ['Slope'], df.columns) 将所有坡度与原始标签包含在一个地方。

请注意,我计算了时间对自身的回归斜率。为什么不?它在那里。它的值为 1.0。伟大的!我可能做对了!

关于python - Pandas Dataframe 中多列的普通最小二乘回归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38406324/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com