python - 从python中的df列中删除特殊字符和字符串
问题描述
目前我的列是对象类型,我正在尝试将其转换为数字类型。但由于其中包含特殊字符和字符串,它会显示错误。
错误:
ValueError: Unable to parse string "7`" at position 3298
代码:
data['col1']=pd.to_numeric(data.col1)
所以,我想从只需要数字和 col1 的列中删除特殊的字符和字符串。有什么建议的解决方案吗?
解决方案
使用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
推荐阅读
- android - 切换到浅色模式时应用程序崩溃
- windows - 打开 Anaconda Prompt 时执行某些命令?
- azure - Azure Function App 是否需要全局唯一名称?
- docker - cgroup rss的内存远高于docker容器内所有进程的内存使用汇总
- kubernetes - Kubernetes 集群主/工作节点
- java - Pb 使用 Ignite 加载和初始化自定义缓存存储
- javascript - 在Javascript中将动态字符串添加到新文件
- javascript - 无法将 json 和文件发送到 Ajax 操作?
- java - 库 org.geotools.util 缺少 org.opengis.util.InternationalString?
- android - 是否可以强制 TabLayout 根据 TabLayout.Tab 文本长度使用动态 TabLayout.Tab 宽度?