我使用潜在Dirichlet分配为5000多个txt文档创建了一个包含20个主题的主题模型。我现在有一个.csv文件,其中包含三列:文档编号,主题编号和文档中主题的概率。看起来像这样(对于文档n°1和n°2):
1 1 0,113
1 4 0,2
1 7 0,156
1 17 0,065
1 18 0,463
2 1 0,44
2 6 0,207
2 14 0,103
2 16 0,126
2 17 0,015
2 18 0,106
基本上,我想为某个主题知道该主题最有可能出现的文档列表。
我想我将必须执行以下操作:
1)对于第1列中的每个相同值(称为doc_number),获取第3列中的最高值(称其为highest_prob)。
2)对于获得的每个doc_number(应该与文档数一样多),在第2列中获取相应的主题号(称其为topic_number)。
3)返回与我感兴趣的特定topic_number相关的doc_number列表。
我对python很陌生,并且不知道如何继续使用csv包或熊猫...
你可以先以中柱并转换为通过。然后,通过柱,并得到列的最大值的用。最后通过以下方式获取所有记录:replace
,
.
probability
float
astype
groupby
document_number
index
probability
idxmax
loc
import pandas as pd
df = pd.DataFrame({'document_number': {0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, 7: 2, 8: 2, 9: 2, 10: 2},
'probability': {0: '0,113', 1: '0,2', 2: '0,156', 3: '0,065', 4: '0,463', 5: '0,44', 6: '0,207', 7: '0,103', 8: '0,126', 9: '0,015', 10: '0,106'},
'topic_number': {0: 1, 1: 4, 2: 7, 3: 17, 4: 18, 5: 1, 6: 6, 7: 14, 8: 16, 9: 17, 10: 18}},
columns = ['document_number','topic_number','probability'])
print (df)
document_number topic_number probability
0 1 1 0,113
1 1 4 0,2
2 1 7 0,156
3 1 17 0,065
4 1 18 0,463
5 2 1 0,44
6 2 6 0,207
7 2 14 0,103
8 2 16 0,126
9 2 17 0,015
10 2 18 0,106
df['probability'] = df.probability.str.replace(',','.').astype(float)
print (df.groupby('document_number')['probability'].idxmax())
1 4
2 5
Name: probability, dtype: int64
print (df.loc[df.groupby('document_number')['probability'].idxmax()])
document_number topic_number probability
4 1 18 0.463
5 2 1 0.440
最后set_index
从列document_number
转换为to_dict
列topic_number
:
print (df.loc[df.groupby('document_number')['probability'].idxmax()]
.set_index('document_number')['topic_number'])
document_number
1 18
2 1
Name: topic_number, dtype: int64
print (df.loc[df.groupby('document_number')['probability'].idxmax()]
.set_index('document_number')['topic_number'].to_dict())
{1: 18, 2: 1}
另一种解决方案是sort_values
按列probability
,然后groupby
进行汇总first
:
print (df.sort_values(by="probability", ascending=False)
.groupby('document_number', as_index=False)
.first())
document_number topic_number probability
0 1 18 0.463
1 2 1 0.440
print (df.sort_values(by="probability", ascending=False)
.groupby('document_number', as_index=False)
.first().set_index('document_number')['topic_number'])
document_number
1 18
2 1
Name: topic_number, dtype: int64
print (df.sort_values(by="probability", ascending=False)
.groupby('document_number', as_index=False)
.first().set_index('document_number')['topic_number'].to_dict())
{1: 18, 2: 1}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句