The error you're encountering, ValueError: Pandas data cast to numpy dtype of object. Check input data with np.asarray(data)., typically occurs when there are non-numeric values in your DataFrame that prevent it from being properly converted to a numeric NumPy array. This is a common issue when preparing data for statistical models like OLS regression.
Let's go through your code step-by-step to identify and fix the problem.
X = reg_df[['org', '% benign', 'c_size', 'balance', 'roles']]
y = reg_df['score']
Create Dummy Variables:
When using pd.get_dummies, ensure that the columns you are converting are categorical. Also verify that the columns '% benign' and 'c_size' are numeric.
python
X = pd.get_dummies(X, columns=['org', 'balance', 'roles'], drop_first=True)
Check for Non-Numeric Values:
Before adding a constant and fitting the model, it's crucial to ensure that all columns in X are numeric. You can check this by examining the data types of each column.
python
print(X.dtypes)
If any columns are not numeric (i.e., they are object type), you need to convert them. Based on your code, '% benign' and 'c_size' should be numeric. If they are not you can convert them as follows:
The errors='coerce' parameter will convert invalid parsing to NaN, which you may need to handle afterwards
5. Add a Constant:
python
X = sm.add_constant(X)
Convert to Numeric (if necessary):
Since you already ensured that all columns are numeric in the previous step this should no longer be necessary. Therefore this line can be removed to avoid errors.
python
# X = X.apply(pd.to_numeric) # Remove this line
Fit the Model:
python
model = sm.OLS(y, X).fit()
print(model.summary())
Complete Fixed Code
Here is the complete, corrected code:
python
import statsmodels.api as sm
import pandas as pd
framework = 'business_goals'
reg_df = df_score[df_score['framework'] == framework]
X = reg_df[['org', '% benign', 'c_size', 'balance', 'roles']]
y = reg_df['score']
X = pd.get_dummies(X, columns=['org', 'balance', 'roles'], drop_first=True)
# Ensure '% benign' and 'c_size' are numeric
X['% benign'] = pd.to_numeric(X['% benign'], errors='coerce')
X['c_size'] = pd.to_numeric(X['c_size'], errors='coerce')
# Check for non-numeric columns
non_numeric_columns = X.select_dtypes(include=['object']).columns
if len(non_numeric_columns) > 0:
raise ValueError(f"Non-numeric columns found: {non_numeric_columns}")
# Add a constant to the model
X = sm.add_constant(X)
# Fit the model
model = sm.OLS(y, X).fit()
print(model.summary())
Additional Notes:
Handling Missing Values:
If pd.to_numeric converts any values to NaN due to invalid entries, you should decide how to handle these missing values. Common approaches include:
Dropping rows with missing values: X.dropna(inplace=True)
Imputing missing values: X.fillna(X.mean(), inplace=True) (or another imputation strategy).
Verification:
After converting columns to numeric and before fitting the model, verify there are no NaN values in X or y, as these will also cause errors.
python
if X.isnull().any().any() or y.isnull().any():
raise ValueError("Missing values detected in X or y.")
By ensuring all columns in X are numeric and handling any missing values, you should be able to fit the OLS model without encountering the ValueError.