删除 pandas 数据框中的所有特殊字符

Remove all special characters in pandas dataframe

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

我试过这样的事情:

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

因为我最近 post 找到了它。 但是当我执行时,特殊字符“'”并没有消失。

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

的事情

a) 只保留字母

b) 只保留数字

c) 保留字母和数字

感谢您的帮助!

只需这样做:

df = df.replace(r'[^0-9a-zA-Z ]', '', regex=True).replace("'", '')

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

使用

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

proof

说明

--------------------------------------------------------------------------------
  [^\w\s]                  any character except word characters (\p{L}, \p{N}, _) 
                           and whitespace (\p{Z})
--------------------------------------------------------------------------------
 |                        OR
--------------------------------------------------------------------------------
  _                        '_'