我的数据框如下所示:

ID topics   text
1     1        twitter is my favorite social media
2     1        favorite social media
3     2        rt twitter tomorrow
4     3        rt facebook today
5     3        rt twitter
6     4        vote for the best twitter
7     2        twitter tomorrow
8     4        best twitter

我想按主题分组,并使用count矢量器(我真的更喜欢使用countvectorize,因为它允许删除多种语言中的停止词,我可以设置3到4克的范围)来计算最频繁的二元图.在获得最频繁的二元图之后,我想创建一个名为"二元图"的新列,并将每个主题最频繁的二元图分配给该列.

我希望我的输出像这样.

ID topics      text                                 biagram
1     1        twitter is my favorite social       favorite social
2     1        favorite social media               favorite  social
3     2        rt twitter tomorrow                 twitter tomorrow
4     2        twitter tomorrow                    twitter tomorrow
5     3        rt twitter                          rt twitter
6     3        rt facebook today           rt twitter 
7     4        vote for the bes twitter               best twitter
8     4        best twitter                        best twitter

请注意,"主题"列不需要按主题排序.我在写这篇文章的时候是为了形象化.

此代码将在600万行数据上运行,因此需要快速.

使用Pandas 最好的方法是什么?如果事情太复杂,我道歉.

推荐答案

Update

您可以使用sklearn:

trom sklearn.feature_extraction.text import CountVectorizer

vect = CountVectorizer(analyzer='word', ngram_range=(2, 2), stop_words='english')
data = vect.fit_transform(df['text'])
bigram = (pd.DataFrame(data=data.toarray(),
                       index=df['topics'],
                       columns=vect.get_feature_names_out())
            .groupby('topics').sum().idxmax(axis=1))
df['bigram'] = df['topics'].map(bigram)
print(df)

# Output
   ID  topics                                 text            bigram
0   1       1  twitter is my favorite social media   favorite social
1   2       1                favorite social media   favorite social
2   3       2                  rt twitter tomorrow  twitter tomorrow
3   4       3                    rt facebook today    facebook today
4   5       3                           rt twitter    facebook today
5   6       4            vote for the best twitter      best twitter
6   7       2                     twitter tomorrow  twitter tomorrow
7   8       4                         best twitter      best twitter

Old answer

您可以使用nltk:

import nltk

to_bigram = lambda x: list(nltk.bigrams(x.split()))
most_common = (df.set_index('topics')['text'].map(to_bigram)
                 .groupby(level=0).apply(lambda x: x.mode()[0][0]))

df['bigram'] = df['topics'].map(most_common)
print(df)

# Output
   ID  topics                                 text              bigram
0   1       1  twitter is my favorite social media  (favorite, social)
1   2       1                favorite social media  (favorite, social)
2   3       2                  rt twitter tomorrow       (rt, twitter)
3   4       3                    rt facebook today      (rt, facebook)
4   5       3                           rt twitter      (rt, facebook)
5   6       4            vote for the best twitter     (best, twitter)
6   7       2                     twitter tomorrow       (rt, twitter)
7   8       4                         best twitter     (best, twitter)

Python相关问答推荐

如何杀死一个进程,我的Python可执行文件以sudo启动?

提高算法效率的策略?

在Python中控制列表中的数据步长

如何在Quarto中的标题页之前创建序言页

Django更新视图未更新

在不中断格式的情况下在文件的特定部分插入XML标签

ValueError:必须在Pandas 中生成聚合值

正则表达式反向查找

如何在微调Whisper模型时更改数据集?

Fake pathlib.使用pyfakefs的类变量中的路径'

如何导入与我试图从该目录之外运行的文件位于同一目录中的Python文件?

捕获脚本和退出代码的多行输出

字符串是批注序列[SEQUENCE[STR]]的有效类型吗?

如何从表示音频的Numy数组中提取持续时间和偏移量?

在Polars中查找给定列的范围内的最大值?

改进积分方程式、Worker关键字非函数拟合的scipy.Integrate.quad_vec性能

如何使用建议值设置不区分大小写的模型

获取文本文件并创建CSV文件

CKEditor更新通知

导入错误:无法导入PerfetoLibrary