W
W
wolverine7772020-07-27 20:41:46
Python
wolverine777, 2020-07-27 20:41:46

Why is iteration replacement not working?

Hello, in the iris dataset, I created a new empty spec column and am trying to replace the names of the irises with numbers, 1, 2 and 3.

For some reason, as a result, all the irises have a number three. What's wrong? Thank you.

iris = sns.load_dataset('iris')

iris['spec'] = ""

for i in iris['species']:
    if i=='setosa':
        iris['spec']=1
    elif i=='versicolor':
        iris['spec']=2
    else:
        iris['spec']=3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dmshar, 2020-07-27
@wolverine777

Because it assigns a value to ALL elements of the column. And since else is triggered in the last iterations of the loop, you get all triples in this column.
iris['spec']=1

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question