首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中将具有字符串和int的dataframe列转换为仅int。

如何在python中将具有字符串和int的dataframe列转换为仅int。
EN

Stack Overflow用户
提问于 2021-05-15 07:23:22
回答 1查看 503关注 0票数 0

我想将下面数据集的权重列转换为1.37作为我的数据集的浮动值,该数据集当前的条目形式是“1.37kg”,它不是浮点数。我正在使用这个数据集来自Kaggle

我正在处理的数据样本:

代码语言:javascript
复制
# 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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-05-15 07:26:36

使用replace()astype()方法:

代码语言:javascript
复制
df['weight']=df['weight'].replace('kg','',regex=True).astype(float)

另一种方法是使用字符串切片和astype()方法:

代码语言:javascript
复制
df['weight']=df['weight'].str[:-2].astype(float)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67544253

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档