我有一个列表如下,
remove_words = ['abc', 'deff', 'pls']
以下是我拥有的列名称为“string”的数据框
data['string']
0 abc stack overflow
1 abc123
2 deff comedy
3 definitely
4 pls lkjh
5 pls1234
我想检查 pandas dataframe 列中 remove_words 列表中的单词,并删除 pandas dataframe 中的这些单词。我想检查单独出现的单词而不与其他单词一起出现。
例如,如果 pandas df 列中有 'abc',请将其替换为 '',但如果它出现在 abc123 中,我们需要保持原样。这里的输出应该是,
data['string']
0 stack overflow
1 abc123
2 comedy
3 definitely
4 lkjh
5 pls1234
在我的实际数据中,remove_words 列表中有 2000 个单词,pandas 数据框中有 50 亿条记录。所以我正在寻找最有效的方法来做到这一点。
我在 python 中尝试了一些东西,但没有成功。有人可以帮我做这件事吗?任何想法都会有所帮助。
谢谢
最佳答案
试试这个:
In [98]: pat = r'\b(?:{})\b'.format('|'.join(remove_words))
In [99]: pat
Out[99]: '\\b(?:abc|def|pls)\\b'
In [100]: df['new'] = df['string'].str.replace(pat, '')
In [101]: df
Out[101]:
string new
0 abc stack overflow stack overflow
1 abc123 abc123
2 def comedy comedy
3 definitely definitely
4 pls lkjh lkjh
5 pls1234 pls1234
关于python - 检查列表中的单词并删除 pandas dataframe 列中的那些单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45447848/