首页 > 解决方案 > 从填充有句子的数据框中删除字母分组和单词列表

问题描述

我有一个df包含未清理文本字符串的数据框

                             phrase
 0           the quick brown br fox
 1   jack and jill went up the hill

我还有一个单词和字母分组列表,我想将remove其称为 remove,如下所示:

['br', and]

在这个例子中,我想要以下输出:

                         phrase
 0          the quick brown fox
 1   jack jill went up the hill

请注意,它不是br保留在“棕色”中,df因为它是较大单词的一部分,但“br”本身已被删除。

我试过了:

df['phrase']=[re.sub(r"\b%remove\b", "", sent) for sent in df['phrase']]

但不能让它正常工作。接下来我可以尝试什么?

标签: pythonpandas

解决方案


将嵌套列表推导与split, tes 成员资格结合使用,in并将拆分后的值连接回来:

L = ['br', 'and']

df['phrase']=[' '.join(x for x in sent.split() if x not in L) for sent in df['phrase']]
print (df)
                       phrase
0         the quick brown fox
1  jack jill went up the hill

推荐阅读