Unexpected error

I was completing the challenge for ‘12: Challenge: Clean a String Column’ and I am stuck when submitting the answer. I’ve looked repeatedly at my code and unfortunately I cannot find what’s wrong with it. Kindly look at my code below and I would greatly appreciate any replies.

The error it seems to be giving is at line 2.

My Code:

# Replacing kgs and kg to convert to numerical
laptops['weight'] = laptops['weight'].str.replace('kgs', '').str.replace('kg','')

# Converting data to float type
laptops['weight'] = laptops['weight'].astype(float)

# Renaming weight column to indicate kg unit
laptops.rename({'weight' : 'weight_kg'}, axis=1, inplace=True)

# Save laptops dataframe to csv, without index labels
laptops.to_csv('laptops_cleaned.csv', index=False)

I expected the answer to be the same as the solution, especially since it’s very close to the solution, but I’m always getting the same error:

KeyErrorTraceback (most recent call last)
<ipython-input-1-26dbe6c8dada> in <module>()
      1 # Replacing kgs and kg to convert to numerical
----> 2 laptops['weight'] = laptops['weight'].str.replace('kgs', '').str.replace('kg','')
      4 # Converting data to float type
      5 laptops['weight'] = laptops['weight'].astype(float)

KeyError: 'weight'

I honestly don’t know what’s wrong with my code! But I’m expecting it to be one of those that you can’t see after a long time looking at the code…

Thanks for any feedback!

Honestly, I don’t really know why you do not succeed in the challenge with your code. As you can see below, it worked for me.

My idea is that you already replaced some strings previously (using str.replace()) when you were trying to find the right solution and, because of that, you changed the datas contained in the dataset at the beginning. Thus it could explain why your actual code does not work. I don’t know if I’m clear…
The best you can do is to click the “restore to initial code” button (just next to the “Submit Answer” button) and copy/paste again your solution. It should work…

I had the same problem with my code when I did that challenge. Here is how I fixed it:

laptops['weight'] = laptops['weight'].astype(str). str.replace('kgs', '').str.replace('kg','')

As you can see, I added “astype(str)”. It seems that the environment has a glitch that makes it not recognize the weight column as a string.

Please let us know if this fixes your problem.

Thank you Sam. I restored my code and it worked!