我在 pandas 数据框中有一些文本
df['mytext']
我还有一个词汇vocab
(单词列表)。
我正在尝试列出并计算每个文档词汇表中的单词
我尝试了以下方法,但对于 10k 文档来说速度相当慢。
如何快速有效地量化 pandas 文本集合中的词汇标记?
OOV_text=df['mytext'].apply(lambda s: ' '.join([ word for word in s.split() if (word not in vocab) ]))
OOV=df['mytext'].apply(lambda s: sum([(word in vocab) for word in s.split()])/len(s.split()))
df.shape[0] 相当大
len(词汇)很大
len(df.mytext 中的唯一单词)<
你可以使用
from collections import Counter
vocab=['word1','word2','word3','2021']
df['mytext_list']=df['mytext'].str.split(' ')
df['count']=df['mytext_list'].apply(lambda c:sum([Counter(c)[w] for w in vocab]))
它应该比您的解决方案更快,因为它使用 pandas 矢量化,然后使用 Counter 方法。
您可以跳过将辅助列保存为“mytest_list”以节省内存使用量。