Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

convert diction with single values to dataframe

let us suppose we have following code :

import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression,Ridge,Lasso,ElasticNet
from sklearn.neighbors import KNeighborsRegressor
from sklearn.tree import DecisionTreeRegressor
from sklearn.svm import SVR
from sklearn.datasets import make_regression
from sklearn.model_selection import train_test_split
X,y =make_regression(n_samples=2000,n_features=20,n_informative =7,noise=3.1,random_state=1)
X_train,X_test,y_train,y_test =train_test_split(X,y,test_size=0.3,random_state=1)
algo_list =[('linear_Regression',LinearRegression()),('Ridge',Ridge()),('Lasso',ElasticNet()),('KNN',KNeighborsRegressor()),('CART',DecisionTreeRegressor()),('SVR',SVR())]
algo_results ={}
for name,model in algo_list:
  model.fit(X_train,y_train)
  algo_results[name] =model.score(X_test,y_test)
print(algo_results)

result of this algorithm is :

{'linear_Regression': 0.999615308811996, 'Ridge': 0.9996150421204321, 'Lasso': 0.8758019197852375, 'KNN': 0.6274472685707742, 'CART': 0.46164502153497877, 'SVR': 0.17305435111869027}

i would like to convert this dictionary to dataframe, here is my code :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

algo_dataframe =pd.DataFrame.from_dict(algo_results)
print(algo_dataframe.head())

but there is error :

ValueError: If using all scalar values, you must pass an index

maybe because it contains single values?how can i fix it?

>Solution :

algo_dataframe =pd.DataFrame(algo_results, index =[0])

Or put your dict in a list

algo_results =[{'linear_Regression': 0.999615308811996, 'Ridge': 0.9996150421204321, 'Lasso': 0.8758019197852375, 'KNN': 0.6274472685707742, 'CART': 0.46164502153497877, 'SVR': 0.17305435111869027}]
algo_dataframe =pd.DataFrame(algo_results)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading