Reputation: 11
from sklearn.datasets import load_iris
data = load_iris()
iris = pd.DataFrame(data.data,columns = data.feature_names)
iris['target_names'] = [data.target_names[i] for i in data.target]
for i in data.target:
iris['target_names'][i] = data.target_names[i]
Why is the first bit of code is giving a different result in comparison to second?
Upvotes: 0
Views: 69
Reputation: 49794
iris['target_names'] = [data.target_names[i] for i in data.target]
generates a list of of the elements data.target_names[i]
for i in data.target:
iris['target_names'][i] = data.target_names[i]
references all of the same pieces, but stores them into:
iris['target_names'][i]
The only way this would generate the same thing as the comprehension is if iris['target_names']
were a list of the same length data.target
and data.target
contained the equivalent of range(len(data.target))
.
To build a comprehension that is the same as the loop (in 2), iris['target_names']
likely needs to be a dict
.
iris['target_names'] = {i: data.target_names[i] for i in data.target}
same as:
for i in data.target:
iris['target_names'][i] = data.target_names[i]
To build a loop that is the same as the comprehension (in 1), you will need to append to a list
like:
iris['target_names'] = []
for i in data.target:
iris['target_names'].append(data.target_names[i])
Same as:
iris['target_names'] = [data.target_names[i] for i in data.target]
Upvotes: 0