python - 从数据框中删除特定字符串
问题描述
我无法从数据集中的这些列中清除字符串“km/kg”、“kmpl”、“CC”和“bhp”
这是示例数据集
Year | Fuel_Type | Mileage | Engine | Power |
2010 | LPG | 26.6 km/kg | 998 CC | 58.16 bhp |
2011 | Diesel | 19.67 kmpl | 1582 CC | 126.2 bhp |
在这种特殊情况下,从数据集的 Engine、Mileage 和 Power 列中删除所有字符,以便只保留数字。
解决方案
只需使用df.replace
和使用regex
模式进行字符串匹配。
df[['Mileage','Engine','Power']] = df[['Mileage','Engine','Power']].replace(to_replace=r'([a-z/]+|[A-Z/]+)', value='', regex=True)
印刷:
Year Fuel_Type Mileage Engine Power
0 2010 LPG 26.6 998 58.16
1 2011 Diesel 19.67 1582 126.2
推荐阅读
- sql-server - SQL Server - 使用存储过程更新多条记录
- regex - 正则表达式仅匹配从文本顶部开始的第一次出现
- python - 尝试在 Python 中加载 .dll 文件。获取 OSError:[WinError 126]。我究竟做错了什么?
- ansible - 过滤地址匹配条件
- swift - 通过 transform.scale 属性为 CAShapeLayer 的路径设置动画
- haskell - 是什么让 Haskell 中的两个类型表达式等价?
- python - Statsmodels 的 Logit.fit_regularized 一直在运行
- javascript - 在 Angular 组件中使用 Tippy.js
- python - 如何将每行中打印的内容连接到 csv?
- python - 搜索行,拉取特定数据