python - 如何在Python中删除数据框中单词的精确匹配?

标签 python regex string

假设以下数据框有一个名为 的列:

df:
   game
0  juegos blue
1  juego red
2  juegos yellow

我想从以下停用词列表中删除这些词:

stopWords = ['juego','juegos']

期望的结果是:

df:
   game
0  blue
1  red
2  yellow

我尝试过:

df['game'] = df['game'].str.replace("|".join(stopWords ), " ")

该函数有效,但它从条目“juegos”中删除了“juego”,只留下“s”:

df:
   game
0  s blue
1   red
2  s yellow

有没有办法仅在完全匹配的情况下删除单词?

最佳答案

你可以使用 pandas DataFrame.replace() 来完成

In [1]: import pandas as pd 
   ...: df = pd.DataFrame({'game': ['juegos blue', 'juego red', 'juegos yellow']}) 
   ...: stop_words = [r'juego\b', r'juegos\b'] 
   ...: df.replace(to_replace={'game': '|'.join(stop_words)}, value='', regex=True, inplace=True) 
   ...: df                                                                                                                                                    
Out[1]: 
      game
0     blue
1      red
2   yellow

In [2]: df = pd.DataFrame({'game': ['juegos blue', 'juego red', 'juegos yellow']}) 
   ...: stop_words = [r'juego\b'] 
   ...: df.replace(to_replace={'game': '|'.join(stop_words)}, value='', regex=True, inplace=True) 
   ...: df                                                                                                                                                    
Out[2]: 
            game
0    juegos blue
1            red
2  juegos yellow

假设停止“单词”以单词边界 \b 结尾。

关于python - 如何在Python中删除数据框中单词的精确匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63078865/

相关文章:

python - 检测曲线边界上的点

c# - 负前瞻行为不符合预期

c# - 为什么字符串类型的默认值是null而不是空字符串?

c - char s[] 和 char *s 有什么区别?

Pythonic 字符串操作

python - 使用 pyodbc 将带日期的数据上传到 MS Access 数据库

python - 在 python 中解析 xml

python - python和mysql命令行中的mysql插入错误

java - 拆分字符串具有带正则表达式的符号(许多管道)

java - 正则表达式静态组问题