Skip to main content
 首页 » 编程设计

python之无法替换 Python pandas 数据框中的特殊字符

2024年09月07日11Terrylee

我在 Windows 中使用 Python 3.5。我有一个数据框,其中 'titles' str 类型列包含标题标题,其中一些具有特殊字符,例如 â、€, ~。

我正在尝试使用 pandas.replace 将它们替换为空格 ''。我尝试了各种迭代,但没有任何效果。我可以替换常规字符,但这些特殊字符似乎不起作用。

代码运行没有错误,但替换根本没有发生,而是返回了原始标题。以下是我已经尝试过的。任何建议将不胜感激。

df['clean_title'] = df['titles'].replace('€','',regex=True) 
df['clean_titles'] = df['titles'].replace('€','') 
df['clean_titles'] = df['titles'].str.replace('€','') 
 
def clean_text(row): 
   return re.sub('€','',str(row)) 
   return str(row).replace('€','') 
df['clean_title'] = df['titles'].apply(clean_text) 

请您参考如下方法:

我们只能假定您将非 ASCI 字符称为“特殊”字符。

要删除 pandas 数据框列中的所有 非 ASCI 字符,请执行以下操作:

df['clean_titles'] = df['titles'].str.replace(r'[^\x00-\x7f]', '') 

请注意,这是一个可扩展的解决方案,因为它适用于任何 非 ASCI 字符。