0

I want to convert the weight column of the below dataset which currently has entries in the form of "1.37 kg" which is not an float value to 1.37 as an float value for my dataset? I am using this dataset from Kaggle.

Sample of data that I am working with:

# dftrain.head()
   laptop_ID Company      Product   TypeName  Inches                    ScreenResolution                         Cpu   Ram               Memory                           Gpu  OpSys  Weight  Price_euros
0          1   Apple  MacBook Pro  Ultrabook    13.3  IPS Panel Retina Display 2560x1600        Intel Core i5 2.3GHz   8GB            128GB SSD  Intel Iris Plus Graphics 640  macOS  1.37kg      1339.69
1          2   Apple  Macbook Air  Ultrabook    13.3                            1440x900        Intel Core i5 1.8GHz   8GB  128GB Flash Storage        Intel HD Graphics 6000  macOS  1.34kg       898.94
2          3      HP       250 G6   Notebook    15.6                   Full HD 1920x1080  Intel Core i5 7200U 2.5GHz   8GB            256GB SSD         Intel HD Graphics 620  No OS  1.86kg       575.00
3          4   Apple  MacBook Pro  Ultrabook    15.4  IPS Panel Retina Display 2880x1800        Intel Core i7 2.7GHz  16GB            512GB SSD            AMD Radeon Pro 455  macOS  1.83kg      2537.45
4          5   Apple  MacBook Pro  Ultrabook    13.3  IPS Panel Retina Display 2560x1600        Intel Core i5 3.1GHz   8GB            256GB SSD  Intel Iris Plus Graphics 650  macOS  1.37kg      1803.60
V1k1ng
  • 35
  • 5

1 Answers1

2

Use replace() and astype() method:

df['weight']=df['weight'].replace('kg','',regex=True).astype(float)

OR

Another way is by using string slicing and astype() method:

df['weight']=df['weight'].str[:-2].astype(float)
Anurag Dabas
  • 23,866
  • 9
  • 21
  • 41