當前位置: 首頁>>技術問答>>正文


如何將Sklearn數據集轉換為Pandas數據集?

如何將數據集從Scikit-learn Bunch對象轉換為Pandas DataFrame?

from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
print(type(data))    #輸出:<class 'sklearn.utils.Bunch'>
data1 = pd. # Is there a Pandas method to accomplish this? 

 

最佳思路

可以手動使用pd.DataFrame構造函數,提供一個numpy數組(data)和列名的列表(columns)。要將所有內容都放在一個DataFrame中,可以使用np.c_[...]將特征和目標(標簽)連接到一個numpy數組中(請注意運算符[]):

import numpy as np
import pandas as pd
from sklearn.datasets import load_iris

# save load_iris() sklearn dataset to iris
# if you'd like to check dataset type use: type(load_iris())
# if you'd like to view list of attributes use: dir(load_iris())
iris = load_iris()

# np.c_ is the numpy concatenate function
# which is used to concat iris['data'] and iris['target'] arrays 
# for pandas column argument: concat iris['feature_names'] list
# and string list (in this case one string); you can make this anything you'd like..  
# the original dataset would probably call this ['Species']
data1 = pd.DataFrame(data= np.c_[iris['data'], iris['target']],
                     columns= iris['feature_names'] + ['target'])

 

第二種思路

對於scikit-learn中的所有數據集,上文”最佳思路”的解決方案不夠通用。例如,它不適用於波士頓住房數據集。我提出了另一種更通用的解決方案。也無需使用numpy。

from sklearn import datasets
import pandas as pd

boston_data = datasets.load_boston()
df_boston = pd.DataFrame(boston_data.data,columns=boston_data.feature_names)
df_boston['target'] = pd.Series(boston_data.target)
df_boston.head()

作為通用函數:

def sklearn_to_df(sklearn_dataset):
    df = pd.DataFrame(sklearn_dataset.data, columns=sklearn_dataset.feature_names)
    df['target'] = pd.Series(sklearn_dataset.target)
    return df

df_boston = sklearn_to_df(datasets.load_boston())

sklearn iris 數據集


參考資料

 

本文由《純淨天空》出品。文章地址: https://vimsky.com/zh-tw/article/4362.html,未經允許,請勿轉載。