Data Cleaning Basics 12/14

Why do I get an error when I tried to do
laptops[“weight”] = laptops[“weight”].str.replace(“kg”,"").str.replace(“kgs”,"").astype(float)?It says ValueError: could not convert string to float: ‘4s’
The correct one was
laptops[“weight”] =laptops[“weight”].str.replace(“kgs”,"").str.replace(“kg”,"").astype(float);
the only difference is the position of “kgs” and “kg”

Hi @naufalza
In the first part of your code “laptops[“weight”].str.replace(“kg”,”")" you replaced all ‘kg’ with empty string.
After that, you are trying to replace ‘kgs’ with the empty string, which is nowhere in the ‘weight’ column.
That’s why the character ‘s’ is left in the elements, which gives an error.

So basically, first you have replace ‘kg’ from the column then replace ‘s’ with the empty string.

laptops[“weight”] = laptops[“weight”].str.replace(“kg”,"").str.replace(“s”,"")


That really makes sense. Thank you!!

1 Like