3
$\begingroup$

I am trying to get the 'data' and the 'target' of the iris setosa database, but I can't. For example, when I load the iris setosa directly from sklearn datasets I get a good result:

Program:

from sklearn import datasets
import numpy as np
iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
print('Class labels:', np.unique(y))

output:

Class labels: [0 1 2]

But if I try to load it directly from extension '.csv' I get the following error:

Program:

import pandas as pd

iris = pd.read_csv('iris.csv', header=None).iloc[:,2:4]

x = iris.data
y = iris.target

output:

'DataFrame' object has no attribute 'data'

Why does this happen?

$\endgroup$
2
$\begingroup$

"sklearn.datasets" is a scikit package, where it contains a method load_iris().

load_iris(), by default return an object which holds data, target and other members in it. In order to get actual values you have to read the data and target content itself.

Whereas 'iris.csv', holds feature and target together.

FYI: If you set return_X_y as True in load_iris(), then you will directly get features and target.

from sklearn import datasets
data,target = datasets.load_iris(return_X_y=True)
$\endgroup$
0
$\begingroup$

If your second snippet program was run (in continuation) on the very same kernel where you ran first snippet program then you will get this error because dataset iris was pre-definied by you and has method data already built-in, provided by Scikit-Learn.

When working with dedicated CSV files, Pandas have different methods that you may make use of, as:

#To show all data(https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.all.html), use:
iris.all

#To get results that you expected, use df.columns (https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.columns.html):
x = iris[iris.columns[0]]
y = iris[iris.columns[1]]

Kindly confirm if your program fetched this error or separate kernels. Or else if this solution fits your requirement, you may chose to mark this as an answer for others learners to get benefited when in doubt.

$\endgroup$
0
$\begingroup$

When we load the iris data directly from sklearn datasets, we don't have to worry about slicing the columns for data and target as sklearn itself would have organized the data in a manner we can use to directly to feed into the model.

But when we are loading from the data from csv file, we have to slice the columns as per our needs and organize it in a way so that it can be fed into in the model. When you execute the below lines after reading csv file using read_csv in pandas

x=iris.data
y=iris.target

you are actually referring to the attributes of the pandas dataframe and not the actual data and target column values like in sklearn. You will have to use iris['data'], iris['target'] to access the column values if it is present in the data set.

$\endgroup$
0
$\begingroup$
from sklearn import datasets
iris = datasets.load_iris()
X = pd.DataFrame(iris.data)
X.columns = ['Sepal.leangth','sepal_width','petal_length','Petal_width']
Y= pd.DataFrame(iris.target)
Y.columns = ['Target']

This might solve the issue!

$\endgroup$
0
$\begingroup$

The Iris Dataset from Sklearn is in Sklearn's Bunch format:

print(type(iris))
print(iris.keys())

output:

<class 'sklearn.utils.Bunch'>
dict_keys(['data', 'target', 'target_names', 'DESCR', 'feature_names', 'filename'])

So, that's why you can access it as:

x=iris.data
y=iris.target

But when you read the CSV file as DataFrame as mentioned by you:

iris = pd.read_csv('iris.csv',header=None).iloc[:,2:4]
iris.head()

output is:

    2   3
0   petal_length    petal_width
1   1.4 0.2
2   1.4 0.2
3   1.3 0.2
4   1.5 0.2

Here the column names are '1' and '2'.

First of all you should read the CSV file as:

df = pd.read_csv('iris.csv')

you should not include header=None as your csv file includes the column names i.e. the headers.

So, now what you can do is something like this:

X = df.iloc[:, [2, 3]] # Will give you columns 2 and 3 i.e 'petal_length' and 'petal_width'
y = df.iloc[:, 4] # Label column i.e 'species'

or if you want to use the column names then:

X = df[['petal_length', 'petal_width']]
y = df.iloc['species']

Also, if you want to convert labels from string to numerical format use sklearn LabelEncoder

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
y = le.fit_transform(y)
$\endgroup$
0
$\begingroup$

You are loading the CSV file without its header! Hence, there is no 'data' column in the dataframe

iris = pd.read_csv('iris.csv', header=None).iloc[:,2:4]

You should use:

iris = pd.read_csv('iris.csv', header=0).iloc[:,2:4]
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.