用熊猫删除停用词

时间:2018-08-19 04:27:45

标签: python pandas dataframe text stop-words

我想从数据帧的列中删除停用词。 列内有需要拆分的文本。

例如,我的数据框如下所示:

ID   Text
1    eat launch with me
2    go outside have fun

我想在text column上应用停用词,因此应该将其拆分。

我尝试过:

for item in cached_stop_words:
    if item in df_from_each_file[['text']]:
        print(item)
        df_from_each_file['text'] = df_from_each_file['text'].replace(item, '')

所以我的输出应该是这样的:

ID   Text
1    eat launch 
2    go fun

这意味着停用词已被删除。 但它无法正常工作。反之亦然,我尝试将数据帧设置为序列,然后循环遍历,但也没有用。

感谢您的帮助。

1 个答案:

答案 0 :(得分:2)

replace(本身)在这里不太适合,因为您要执行 partial 字符串替换。您需要基于正则表达式的替换。

一种简单的解决方案,当停用词的数量可控时,则使用str.replace

p = re.compile("({})".format('|'.join(map(re.escape, cached_stop_words))))
df['Text'] = df['Text'].str.lower().str.replace(p, '')

df
   ID               Text
0   1       eat launch  
1   2   outside have fun

如果性能很重要,请使用列表理解。

cached_stop_words = set(cached_stop_words)
df['Text'] = [' '.join([w for w in x.lower().split() if w not in cached_stop_words]) 
    for x in df['Text'].tolist()]

df
   ID              Text
0   1        eat launch
1   2  outside have fun
相关问题