在python中从df列中删除特殊字符和字符串
当前我的列是对象类型,我正在尝试将其转换为数值类型。 但是它显示了错误,因为其中包含特殊的字符和字符串 错误:在python中从df列中删除特殊字符和字符串,python,pandas,numpy,dataframe,Python,Pandas,Numpy,Dataframe,当前我的列是对象类型,我正在尝试将其转换为数值类型。 但是它显示了错误,因为其中包含特殊的字符和字符串 错误: ValueError: Unable to parse string "7`" at position 3298 代码: 所以,我想从只需要number和col1的列中删除特殊的char和string。 任何建议的解决方案?使用str。用regex模式替换 Ex: df = pd.DataFrame({"col1": ["7`", "123", "AS123", "*&%3R
ValueError: Unable to parse string "7`" at position 3298
代码:
所以,我想从只需要number和col1的列中删除特殊的char和string。
任何建议的解决方案?使用
str。用regex模式替换
Ex:
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
输出:
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
谢谢你能详细说明一下这个“r”[^\d]”的作用吗?替换除数字以外的所有内容。