1

So I have a Dataset which has a column containing name of colors(red, blue, green) and I want to convert these string values into int/float to fit into classifier. I was planning on using Python dictionary with keys as name of color and values as numbers. This was my code:

color_dict = {'red':1, 'blue':2, 'green':3}
for i in train['column_name']:
     train['column_name'][i] = color_dict[i]
print(train['column_name'])

Sadly, this did not work. What should I do differently to make it work?

1
  • I assume you're using Pandas, so I added the pandas tag for you. If that's incorrect, you can edit to fix it. Commented Sep 20, 2021 at 4:34

1 Answer 1

2

The answer is in the question :)

train["column_name"] = train["column_name"].map(color_dict)

See the docs for map.

The reason your solution didn't work is a bit tricky. When you access a value like you did (using chained brackets), you're working on a copy of the DataFrame object. Instead, use train.loc[i, "column_name"] = color_dict[i] to set the a single value in a column. See here for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.