The error you're encountering typically arises when there are non-numeric values in your DataFrame that you're trying to use for regression. Even though you've applied pd.to_numeric, it seems like some columns might still contain non-numeric values or NaNs that are causing issues.
Here's a step-by-step approach to debug and fix this issue:
- Check for Non-Numeric Values: Ensure that all columns in
X are numeric after the pd.get_dummies and pd.to_numeric steps.
- Handle NaNs: Ensure there are no NaN values in your DataFrame.
- Convert Columns to Numeric: Use
pd.to_numeric with error handling to convert columns to numeric and deal with any conversion errors.
Here’s how you can modify your code to include these checks and conversions:
import pandas as pd
import statsmodels.api as sm
from sklearn.preprocessing import LabelEncoder
# Filter the dataframe
framework = 'business_goals'
reg_df = df_score[df_score['framework'] == framework]
# Define features and target
X = reg_df[['org', '% benign', 'c_size', 'balance', 'roles']]
y = reg_df['score']
# One-hot encode categorical variables
X = pd.get_dummies(X, columns=['org', 'balance', 'roles'], drop_first=True)
# Ensure all columns are numeric and handle any conversion errors
for col in X.columns:
X[col] = pd.to_numeric(X[col], errors='coerce') # Convert to numeric, coerce errors to NaN
# Check for and handle NaN values (you can choose to fill them or drop them)
X = X.dropna() # This will drop rows with NaN values; alternatively, you can fill them
# Add a constant to the model
X = sm.add_constant(X)
# Fit the model
model = sm.OLS(y, X).fit()
print(model.summary())
Explanation:
- One-Hot Encoding:
pd.get_dummies is used to convert categorical variables into dummy/indicator variables.
- Numeric Conversion with Error Handling:
pd.to_numeric(errors='coerce') converts columns to numeric types, turning any errors into NaNs.
- Handling NaNs:
X.dropna() drops rows with NaN values. You can also use X.fillna(X.mean()) to fill NaNs with the mean of the column if that suits your data better.
- Adding Constant:
sm.add_constant(X) adds a constant term to the model.
- Fitting the Model: Finally, the model is fitted and summarized.
This should help you avoid the ValueError and successfully fit your regression model.