过滤数据帧的行根据最大列值

问题描述:


我有此df数据帧:过滤数据帧的行根据最大列值

 artist    track class1 class2  class3 
0 Portishead    Roads 0.98 0.02   0.0 
1 Yo La Tengo  Our Way to Fall 0.14 0.86   0.0 
2 Radiohead Fake Plastic Trees 0.03 0.97   0.0 

给出的这些用户输入:

input_value = 0.8 
input_class = 'class2' 

我使用了根据数据帧中重新排序下面的代码class2最大值:

for col in df.ix[:,'class1':'class3']: 
    if col == input_class: 
     reordered_df = df.iloc[(df[input_class] - input_value).argsort()] 

像这样:

1 Yo La Tengo  Our Way to Fall 0.14 0.86   0.0 
2 Radiohead Fake Plastic Trees 0.03 0.97   0.0 
0 Portishead    Roads 0.98 0.02   0.0 

不过,我仍然需要满足一类条件,即等级2的值必须是每个行中最高浮动值。换句话说:

0 Portishead    Roads 0.98 0.02   0.0 

应该放弃,因为最大值属于另一个类。

如何在上面的代码片段中插入此条件?

+0

您的df和reorded_df没有相同的值。请再看一遍。 –

找到沿行的max行,比较class2,并相应地丢弃。

reordered_df 
     artist    track class1 class2 class3 
1 Yo La Tengo  Our Way to Fall 0.14 0.86  0.0 
2 Radiohead Fake Plastic Trees 0.03 0.97  0.0 
0 Portishead    Roads 0.98 0.02  0.0 

reordered_df[reordered_df.max(1) == reordered_df.class2] 
     artist    track class1 class2 class3 
1 Yo La Tengo  Our Way to Fall 0.14 0.86  0.0 
2 Radiohead Fake Plastic Trees 0.03 0.97  0.0 
+0

您能否使用上面的代码片段来编辑您的解决方案?我需要保留两个数据帧:'df'和'reordered_df' – outkast

+0

@outkast你不需要for循环。另请参阅编辑。 –