当数据位于 pandas 中时,如何使用 Statsmodels 模块执行多元线性回归

问题描述 投票:0回答:1

我正在尝试使用两个数据帧中的数据进行 MLR,但其中一个数据帧的大小与另一个数据帧的大小不同,因此我的 endog 和 exog 大小不匹配。我想知道是否有人可以帮助我了解如何纠正此问题并获得有效的 MLR。

附上所做的尝试:

X = Reddit_WSB[['Sentiment_score (Body based)','Sentiment_score (Title based)']].values.reshape(-1,1)
X = X.iloc[:min_length]
y = final_df_twitter['Close'] 
y= y.iloc[;min_length]
X = sm.add_constant(X)
model = sm.OLS(y, X).fit()
print(model.summary())

不是专业编码员,所以非常感谢您的意见!预先感谢您!

final_df_twitter 的上下文是 df 中一长串股票的收盘价。

期待与我的单反相机类似的输出,我读过其他帖子,但没有发现它们对解决我的问题有帮助,我很可能误解了,但仍然很感激:)

python pandas dataframe statsmodels sentiment-analysis
1个回答
0
投票

请检查这个:

import statsmodels.api as sm

# Assuming Reddit_WSB and final_df_twitter are your pandas DataFrames

# Concatenate the two independent variables horizontally
X = Reddit_WSB[['Sentiment_score (Body based)', 'Sentiment_score (Title based)']]

# Ensure that the shapes of X and y match
min_length = min(len(X), len(final_df_twitter['Close']))

# Slice X and y to match the minimum length
X = X.iloc[:min_length]
y = final_df_twitter['Close'].iloc[:min_length]

# Add a constant column to the independent variables
X = sm.add_constant(X)

# Fit the multiple linear regression model
model = sm.OLS(y, X).fit()

# Print the summary of the model
print(model.summary())

这里您应该拥有完全相同数量的记录。 删除一些记录可能会有点问题。

您还可以用 null 验证空记录并在开始时减少它。

© www.soinside.com 2019 - 2024. All rights reserved.