使用corr()方法实现sklearnbuck对象iris

2024-03-29 08:03:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我假设在下面的代码中,iris是一个专门为sklearn/dataset设计的bunch对象。在

# import load_iris function from datasets module
from sklearn.datasets import load_iris

# save "bunch" object containing iris dataset and its attributes
iris = load_iris()

当我试图理解它是什么类型的物体时,它说的是束团物体。在

^{pr2}$

现在,如果我需要使用corr()方法来计算每对属性之间的标准关联,则需要在dataframe上工作,而不是在bunch对象上。在

我该怎么做?我能在上面表演吗虹膜数据?我知道这是一个数组。不是数据帧。在

# check the types of the features
print(type(iris.data))
Out[5]:
<class 'numpy.ndarray'>

现在,如果我使用了seaborne的内置数据集或来自实际数据源的数据集,它就不会有这个问题。在这里虹膜腐蚀()工作正常。是的,这里iris是数据帧。在

iris = sns.load_dataset("iris")
type(iris)
Out[7]:
pandas.core.frame.DataFrame
iris.corr()
Out[8]:

              sepal_length  sepal_width  petal_length  petal_width
sepal_length      1.000000    -0.117570      0.871754     0.817941
sepal_width      -0.117570     1.000000     -0.428440    -0.366126
petal_length      0.871754    -0.428440      1.000000     0.962865
petal_width       0.817941    -0.366126      0.962865     1.000000

如何在前面的示例中运行corr()?使用sklearn bunch对象?如何将sklearn bunch对象转换为dataframe?或转换虹膜数据nArray到dataframe?在


Tags: 数据对象irisdataframeloadsklearnoutwidth
1条回答
网友
1楼 · 发布于 2024-03-29 08:03:54

在查看了How to convert a Scikit-learn dataset to a Pandas dataset?处的响应之后,下面可能是答案。感谢大家的指点。在

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

data = load_iris()

我们可以使用np.column_堆栈. 在

^{pr2}$

输出:

^{3}$

现在,我们可以通过将target_names转换为dictionary来替换,并添加一个新列:

df['label'] = df.target.replace(dict(enumerate(data.target_names)))
print(df.head())

输出:

sepal length (cm)  sepal width (cm)  petal length (cm)  petal width (cm)     target  label 
0                5.1               3.5                1.4               0.2     0.0     setosa
1                4.9               3.0                1.4               0.2     0.0     setosa
2                4.7               3.2                1.3               0.2     0.0     setosa
3                4.6               3.1                1.5               0.2     0.0     setosa
4                5.0               3.6                1.4               0.2     0.0     setosa

相关问题 更多 >