如何将 Scikit-learn 数据集转换为 Pandas 数据集 [英] How to convert a Scikit-learn dataset to a Pandas dataset

查看:27
本文介绍了如何将 Scikit-learn 数据集转换为 Pandas 数据集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数据从 Scikit-learn Bunch 对象转换为 Pandas DataFrame?

How do I convert data from a Scikit-learn Bunch object to a Pandas DataFrame?

from sklearn.datasets import load_iris
import pandas as pd
data = load_iris()
print(type(data))
data1 = pd. # Is there a Pandas method to accomplish this?

推荐答案

手动,你可以使用 pd.DataFrame 构造函数,给出一个 numpy 数组 (data) 和一个列名称列表 (columns).要在一个 DataFrame 中包含所有内容,您可以使用 np.c_[...] 将特征和目标连接到一个 numpy 数组中(注意 []):

Manually, you can use pd.DataFrame constructor, giving a numpy array (data) and a list of the names of the columns (columns). To have everything in one DataFrame, you can concatenate the features and the target into one numpy array with np.c_[...] (note the []):

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 数据集转换为 Pandas 数据集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆