熊猫从数据框中提取子集

时间:2020-03-20 22:14:37

标签: python pandas dataframe

我有一个熊猫数据框,如下所示:

 index  Validation_Set  Topics   Alpha       Beta  Coherence
 0      75% Corpus      14         0.5        0.5   0.501483
 1      75% Corpus      14         0.5  symmetric   0.481676
 2     100% Corpus      14  asymmetric        0.5   0.500620
 3     100% Corpus      14         0.5  symmetric   0.492288
 4      75% Corpus      12         0.5        0.5   0.511823
 5      75% Corpus      12         0.5  symmetric   0.477614
 6     100% Corpus      12  asymmetric        0.5   0.489424
 7     100% Corpus      12         0.5  symmetric   0.541270
 8      75% Corpus       4         0.5        0.5   0.515683
 9      75% Corpus       4         0.5  symmetric   0.430614
10     100% Corpus       4  asymmetric        0.5   0.489324
11     100% Corpus       4         0.5  symmetric   0.473570

以此类推...这些是来自几个参数调整测试的结果。

现在,我只想提取关于最佳模型的所有信息(对参数进行的所有测试),该模型是在完整验证集上达到“一致性”最高值的那个(或可能不止一个)模型( 100%语料库)。

在此示例中,我将得到 [错误,请参阅编辑]

 index  Validation_Set  Topics   Alpha       Beta  Coherence
 7     100% Corpus      12         0.5  symmetric   0.541270

我设法通过这种方式(“ df是完整的数据帧”)检索了具有最高“相干性”值的行:

corpus_100 = df[df['Validation_Set']=='100% Corpus']
topics_num = df.iloc[[corpus_100['Coherence'].idxmax()]]['Topics'].values[0]
opt_model = corpus_100[corpus_100['Topics']==topics_num]

并且正在工作,但这确实是一团糟,然后我正在寻找一种更清晰的方法来实现此目的。

谢谢!

编辑:真的很抱歉,但是所需的输出中有一个错字,实际上是:

 4      75% Corpus      12         0.5        0.5   0.511823
 5      75% Corpus      12         0.5  symmetric   0.477614
 6     100% Corpus      12  asymmetric        0.5   0.489424
 7     100% Corpus      12         0.5  symmetric   0.541270

2 个答案:

答案 0 :(得分:1)

尝试一下,

df[df['Coherence']==df['Coherence'].max()]

df[df['column']==value]过滤数据框以查找所需内容。

df['column']max()返回“ column”中的最大值。

将它们放在一起将返回具有Coherence最大值的数据框的行

答案 1 :(得分:0)

看起来nlargest()正是您需要的

df[df['Validation_Set']=='100% Corpus'].nlargest(1,'Coherence')

    index   Validation_Set  Topics  Alpha   Beta        Coherence
    7       100%Corpus      12      0.5     symmetric   0.54127