generate dataframe of model predictions by looping through dictionary of models

Viewed 27

I would like to loop through a dictionary like this:

models = {'OLS': LinearRegression(),
         'Lasso': Lasso(),
         'LassoCV': LassoCV(n_alphas=300, cv=3)}

and then i want to generate a dataframe of the each model's predictions.

So far I wrote this to code, which only generates arrays of each result:

predictions = []

for i in models:   
    predictions.append(models[i].fit(X_train,y_train).predict(X_test))

As the final result, I want a dataframe with each column labelled by the key in the dictionary and the result values associated with the model key name inside the column.

Thank you!

1 Answers

Instead of appending the predictions to the list, you can directly insert the predictions into a data frame.

Code:

import pandas as pd
models = {'OLS': LinearRegression(),
         'Lasso': Lasso(),
         'LassoCV': LassoCV(n_alphas=300, cv=3)}
df = pd.DataFrame()
for i in models:
  df[i] = models[i].fit(X_train,y_train).predict(X_test)   
Related