为了账号安全,请及时绑定邮箱和手机立即绑定

NLP 生成按列中的值分组的并置三元组数据框

NLP 生成按列中的值分组的并置三元组数据框

HUWWW 2021-11-02 09:52:11
我有以下示例数据框。让我们假设每个字母实际上都是一个单词。例如,a = 'ant'和b = 'boy'。id  words1   [a, b, c, d, e, f, g]1   [h, I, o]1   1   [a, b, c]2   [e, f, g, m, n, q, r, s]2   [w, j, f]3   [l, t, m, n, q, s, a]3   [c, d, e, f, g]4   4   [f, g, z]创建上述示例数据框的代码:import pandas as pd d = {'id': [1, 1, 1, 1, 2, 2, 3, 3, 4, 4], 'words': [['a', 'b', 'c', 'd', 'e', 'f', 'g'], ['h', 'I', 'o'], '', ['a', 'b', 'c'], ['e', 'f', 'g', 'm', 'n', 'q', 'r', 's'], ['w', 'j', 'f'], ['l', 't', 'm', 'n', 'q', 's', 'a'], ['c', 'd', 'e', 'f', 'g'], '',  ['f', 'g', 'z']]}df = pd.DataFrame(data=d)我在其上运行以下 NLP 代码以执行以下操作: 给我一个从“单词”字段并置在一起的各种 3 词组合的计数。from nltk.collocations import *from nltk import ngramsfrom collections import Countertrigram_measures = nltk.collocations.BigramAssocMeasures()finder = BigramCollocationFinder.from_documents(df['words'])finder.nbest(trigram_measures.pmi, 100) s = pd.Series(df['words'])ngram_list = [pair for row in s for pair in ngrams(row, 3)]counts = Counter(ngram_list).most_common()df = pd.DataFrame.from_records(counts, columns=['gram', 'count'])示例结果假设输出如下(数据值是假的):gram                          count a, b, c                       13c, d, e                       9g, h, i                       6q, r, s                       1问题是我希望将结果输出按“id”字段拆分。 我想要的样本输出如下(数据是假的和随机的):id   gram                          count 1    a, b, c                       131    c, d, e                       91    g, h, i                       61    q, r, s                       12    a, b, c                       62    w, j, f                       33    l, t, m                       43    e, f, g                       24    f, g, z                       1我如何实现这一目标?...通过“id”字段获取结果?
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 160 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号