python - 如何在python中将同时具有字符串和int的数据框的列转换为仅int
问题描述
我想将以下数据集的重量列转换为“1.37 kg”形式的条目,它不是一个浮点值到1.37作为我的数据集的浮点值?我正在使用来自 Kaggle 的这个数据集。
我正在使用的数据样本:
# 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
解决方案
用途replace()
及astype()
方法:
df['weight']=df['weight'].replace('kg','',regex=True).astype(float)
或者
另一种方法是使用字符串切片和astype()
方法:
df['weight']=df['weight'].str[:-2].astype(float)
推荐阅读
- r - 使用正则表达式从R中的字符串中提取数字
- c# - 基于主下拉列表级联两个下拉列表
- angular - 在 Angular 中动态配置 Firebase 环境
- java - 如何在 Java 中获取当前鼠标指针类型?
- sre - 如何以及在哪里学习站点可靠性工程课程?
- java - 为什么用 .bat 编写的命令在 java 中无限运行?
- python - 根据元组列表中的索引值从数据框中提取值
- node.js - 如何部署 nodejs 和 express 到 AWS EC2 实例
- javascript - 从用户那里获取 2 个号码并显示这两个号码之间的范围
- r - 为什么在我的工作笔记本电脑上安装软件包时出现“无法锁定目录”错误