首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >来自pandas专栏的Ngrams

来自pandas专栏的Ngrams
EN

Stack Overflow用户
提问于 2020-03-06 19:09:27
回答 1查看 393关注 0票数 1

我有一个pandas数据框架,包含以下各列:

第1列

代码语言:javascript
复制
['if', 'you', 'think', 'she', "'s", 'cute', 'now', ',', 'you', 'should', 'have', 'see', 'her', 'a', 'couple', 'of', 'year', 'ago', '.']
['uh', ',', 'yeah', '.', 'just', 'a', 'fax', '.']

第2列

代码语言:javascript
复制
if you think she 's cute now , you should have see her a couple of year ago .
uh , yeah . just a fax .

等。

我的目标是计算数据帧的二元、三元、四元(具体地说,列2,它已经进行了词条分类)。

我尝试了以下几种方法:

代码语言:javascript
复制
import nltk
from nltk import bigrams
from nltk import trigrams

trig = trigrams(df ["Column2"])
print (trig)

但是,我有以下错误

代码语言:javascript
复制
<generator object trigrams at 0x0000013C757F1C48>

我的最终目标是能够打印出最上面的X bi gram,trigram等。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-03-06 19:13:24

首先对所有三元组使用列表理解和split和flatten:

代码语言:javascript
复制
df = pd.DataFrame({'Column2':["if you think she cute now you if uh yeah just",
                              'you think she uh yeah just a fax']}) 

from nltk import trigrams

L = [x for x in df['Column2'] for x in trigrams(x.split())]
print (L)
[('if', 'you', 'think'), ('you', 'think', 'she'), ('think', 'she', 'cute'), 
 ('she', 'cute', 'now'), ('cute', 'now', 'you'), ('now', 'you', 'if'), 
 ('you', 'if', 'uh'), ('if', 'uh', 'yeah'), ('uh', 'yeah', 'just'), 
 ('you', 'think', 'she'), ('think', 'she', 'uh'), ('she', 'uh', 'yeah'),
 ('uh', 'yeah', 'just'), ('yeah', 'just', 'a'), ('just', 'a', 'fax')]

然后通过collections.Counter计算元组

代码语言:javascript
复制
from collections import Counter
c = Counter(L)
print (c)
Counter({('you', 'think', 'she'): 2, ('uh', 'yeah', 'just'): 2, ('if', 'you', 'think'): 1,
         ('think', 'she', 'cute'): 1, ('she', 'cute', 'now'): 1, ('cute', 'now', 'you'): 1,
         ('now', 'you', 'if'): 1, ('you', 'if', 'uh'): 1, ('if', 'uh', 'yeah'): 1, 
         ('think', 'she', 'uh'): 1, ('she', 'uh', 'yeah'): 1, 
         ('yeah', 'just', 'a'): 1, ('just', 'a', 'fax'): 1})

对于顶值,请使用collections.Counter.most_common

代码语言:javascript
复制
top = c.most_common(5)
print (top)
[(('you', 'think', 'she'), 2), (('uh', 'yeah', 'just'), 2), 
 (('if', 'you', 'think'), 1), (('think', 'she', 'cute'), 1),
 (('she', 'cute', 'now'), 1)]
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/60562874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档