python - 跨数据框迭代函数

标签 python pandas loops lda topic-modeling

我有一个包含预处理在线评论的数据集,每行包含来自在线评论的单词。我正在执行潜在狄利克雷分配过程,以从整个数据帧中提取主题。现在,我想根据名为 get_document_topics 的 LDA 函数为每行数据分配主题。

我从来源找到了一个代码,但它只打印文档分配给每个主题的概率。我正在尝试将代码迭代到所有文档并返回到相同的数据集。这是我找到的代码...

text = ["user"]
bow = dictionary.doc2bow(text)
print "get_document_topics", model.get_document_topics(bow)
### get_document_topics [(0, 0.74568415806946331), (1, 0.25431584193053675)]

这就是我想要得到的......

                  stemming   probabOnTopic1 probOnTopic2 probaOnTopic3  topic 
0      [bank, water, bank]              0.7          0.3           0.0      0 
1  [baseball, rain, track]              0.1          0.8           0.1      1
2     [coin, money, money]              0.9          0.0           0.1      0 
3      [vote, elect, bank]              0.2          0.0           0.8      2

这是我正在编写的代码...

def bow (text):
    return [dictionary.doc2bow(text) in document]

df["probability"] = optimal_model.get_document_topics(bow)
df[['probOnTopic1', 'probOnTopic2', 'probOnTopic3']] = pd.DataFrame(df['probability'].tolist(), index=df.index)

最佳答案

稍微不同的方法@Christabel,其中包括阈值为 0.7 的其他请求:

import pandas as pd

results = []

# Iterate over each review
for review in df['review']:
  bow = dictionary.doc2bow(review)
  topics = model.get_document_topics(bow)

  #to a dictionary
  topic_dict = {topic[0]: topic[1] for topic in topics}
  #get the prob
  max_topic = max(topic_dict, key=topic_dict.get)

  if topic_dict[max_topic] > 0.7:
    topic = max_topic
  else:
    topic = 0

  topic_dict['topic'] = topic
  results.append(topic_dict)

#to a DF
df_topics = pd.DataFrame(results)
df = df.merge(df_topics, left_index=True, right_index=True)

它对您有帮助吗? 然后,您可以将此代码放置在函数内部,并使用“0.70”值作为外部参数,以便使其可在不同的用例中使用。

关于python - 跨数据框迭代函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74982496/

相关文章:

python - 使用 numba 加快拍摄速度?

node.js - Node JS 如何处理缓慢的 http 请求?

Python 卡住应用程序文件类型

Python 从多个文件写入会覆盖以前的内容

python - 提升对历史 Twitter 数据访问的时间跨度

python - 按照特定的规则集计算一个新的数据框

python - pandas,python : collecting, 使用和保存实时数据

python - 如何使用循环检查输入是否已存在于 Python 文件中并追加(如果是新的)?

c - 沿对角线循环遍历 2-dim 矩阵,但反之

Python 链表 O(1) 插入/删除