首页 > 解决方案 > 从数据框中删除特定字符串

问题描述

我无法从数据集中的这些列中清除字符串“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 列中删除所有字符,以便只保留数字。

标签: pythonstringdataframe

解决方案


只需使用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 

推荐阅读