【发布时间】:2022-01-14 12:53:47
【问题描述】:
我有一个列表a = ['apples', 'bananas', 'oranges', 'grapes']
还有一个包含一列短语的数据框
| b | c |
|---|---|
| there are 5 apples | there are 5 |
| here are 3 pears | here are 3 pears |
| i want 2 grapes | i want 2 |
我想在我的数据框中有另一列从列表 a 中删除单词(例如在数据框列 c 中)。它们需要完全匹配。
在搜索了一些正则表达式后,我想出了这个,但它似乎无法正常工作。
regex = re.compile('|'.join(re.escape(x) for x in a), re.IGNORECASE)
removed = []
for i in df['b']:
words = re.findall(regex, str(i))
removed.append(words)
df['c']=removed
df
也得到了这个错误:位置括号不平衡
【问题讨论】:
-
ideone.com/RLoUoT 不会抛出这个异常。
标签: python regex pandas dataframe