Single-line code generates different float values vesus separate lines

Screen Link:

Why does this code result in the “weights” column equalling 1.37, 1.7, 1.5, etc.?

**laptops["weight"] = laptops["weight"].str.replace("kg","")**
**laptops["weight"] = laptops["weight"].str.replace("s","")**
**laptops["weight"].astype(float)**
laptops.rename({"weight":"weight_kg"}, axis=1, inplace=True)
laptops.to_csv("laptops_cleaned.csv", index=False)

Whereas this code results in 1.37, 1.70, 1.50, etc.?

**laptops["weight"] = laptops["weight"].str.replace("kg","").str.replace("s","").astype(float)**
laptops.rename({"weight": "weight_kg"}, axis=1, inplace=True)
laptops.to_csv('laptops_cleaned.csv',index=False)
laptops.to_csv("laptops_cleaned.csv", index=False)

Thanks!

1 Like

Hello,

In the above code, the typecasted weight column is not assigned back to the weight column of laptops. Most pandas methods return a modified dataframe rather than modifying the dataframe directly. You will see a similar behaviour if you use str.replace but didn’t assign the modified column to laptops["weight"].

You can verify that no column type change happened in the above code by running laptops.info(); you’ll see that weight will have the type object instead of float.

Modifying the line to laptops["weight"] = laptops["weights"].astype(float) should give the same result as the second code.

3 Likes