假设以下数据框有一个名为
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/