293-12, why can't I do 2 separate str.replace?

Screen Link:

My Code:

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

laptops['weight'] = laptops['weight'].astype(float)

What I expected to happen:
I imagine it would first find kg and replace with blank, then find kgs and replace with blank. Then convert to float

What actually happened:

ValueErrorTraceback (most recent call last)
<ipython-input-1-90d03698eded> in <module>()
      2 laptops['weight'] = laptops['weight'].str.replace('kgs','')
      3 
----> 4 laptops['weight'] = laptops['weight'].astype(float)
2 Likes

Hi @vasatrya, welcome back to the forum. I think I found another post that might have the answer to your question. Please check if this fixes your issue and don’t hesitate to ask further if not. :blush:

5 Likes

I just made the same mistake, the error was bagging me to see it but i didn’t understand it soon after i went to see my dataframe and i saw there is an “s” in weight column.
so it’s always i guess to see your dataframe or you series before and after.

2 Likes

Thank you. i got it.

After i implemented your suggestion. The kg didn’t go away
laptop_weight = laptops[“weight”].head()

solution 1

laptop_weight = laptops[“weight”].str.replace(“kgs”,"").str.replace(“kg”,"").astype(float)
#laptop_weight = laptops[“weight”].str.replace(“kgs”,"").astype(float)
#laptop_weight = laptops[“weight”].astype(float)
laptop_weight_uniq = laptop_weight.unique()
#solution 2
laptops.rename({‘weight’: ‘weight_kg’}, axis = 1, inplace = True)
print(laptops.columns)
#solution 3
laptops.to_csv(‘laptops_cleaned.csv’, index=False)

1 Like