2

我无法从我的 pandas 数据框中删除所有特殊字符。你能帮我吗?

我尝试过这样的事情:

df = df.replace(r'\W+', '', regex=True)

因为我在最近的一篇文章中找到了它。但是当我执行时,特殊字符“'”例如并没有消失。

我知道在 PostgresSQL 中有类似[^\w]获取特定列表的东西。python中是否有类似的东西可以做类似的事情

a) 只保留字母

b) 只保留数字

c) 保留字母和数字

谢谢您的帮助!

4

2 回答 2

2

[^0-9a-zA-Z ]匹配 Unicode 字母和数字,这将删除太多。

利用

df = df.replace(r'[^\w\s]|_', '', regex=True)

证明

解释

--------------------------------------------------------------------------------
  [^\w\s]                  any character except word characters (\p{L}, \p{N}, _) 
                           and whitespace (\p{Z})
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  _                        '_'
于 2020-12-19T00:16:32.860 回答
1

只需这样做:

df = df.replace(r'[^0-9a-zA-Z ]', '', regex=True).replace("'", '')
于 2020-12-18T12:40:01.047 回答