-3

I am trying to learn scikit learn (sklearn). Following is a part of code trying to create a data frame with statsmodels.api from iris dataset. But I'm not sure how the for loop works and the datatypes of iris.target_names[x] & target from sci-kit. Can anyone please explain?

from sklearn import datasets ## Get dataset from sklearn

## Import the dataset from sklearn.datasets
iris = datasets.load_iris()

## Create a data frame from the dictionary
species = [iris.target_names[x] for x in iris.target]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
Dami
  • 677
  • 6
  • 12
  • 1
    It is a list comprehension: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions – LeKhan9 Jul 09 '19 at 17:43
  • 3
    Possible duplicate of [What does "list comprehension" mean? How does it work and how can I use it?](https://stackoverflow.com/questions/34835951/what-does-list-comprehension-mean-how-does-it-work-and-how-can-i-use-it) – wjandrea Jul 09 '19 at 17:44

2 Answers2

2

This is functionally equivalent to the following:

species = []
for x in iris.target:
    species.append(iris.target_names[x])

In essence it is applying a function on every element x in the iterable and creating a list out of the results.

Performing an operation over a list this way is slightly faster than the previously mentioned method and is more readable (in my opinion).

1

It is list comprehension and it do

species = []

for x in iris.target:
    val = iris.target_names[x]
    species.append(val)

for gets values one-by-one from column iris.targetand assigns to x and then it use this x to get value from column iris.target_names and appends this value on list `species.

So it converts values target to values target_name

furas
  • 134,197
  • 12
  • 106
  • 148