首页 > 解决方案 > 从python中的df列中删除特殊字符和字符串

问题描述

目前我的列是对象类型,我正在尝试将其转换为数字类型。但由于其中包含特殊字符和字符串,它会显示错误。

错误:

ValueError: Unable to parse string "7`" at position 3298

代码:

data['col1']=pd.to_numeric(data.col1)

所以,我想从只需要数字和 col1 的列中删除特殊的字符和字符串。有什么建议的解决方案吗?

标签: pythonpandasnumpydataframe

解决方案


使用str.replace正则表达式模式。

前任:

df = pd.DataFrame({"col1": ["7`", "123", "AS123", "*&%3R4"]})
print(pd.to_numeric(df['col1'].str.replace(r"[^\d]", "")))

输出:

0      7
1    123
2    123
3     34
Name: col1, dtype: int64

推荐阅读