Pandas pivot table 选择具有最大值的行

Pandas pivot table selecting rows with maximum values

我有 pandas 数据框:

df

Id      Name        CaseId       Value 
82      A1          case1.01     37.71 
1558    A3          case1.01     27.71 
82      A1          case1.06     29.54 
1558    A3          case1.06     29.54 
82      A1          case1.11     12.09 
1558    A3          case1.11     32.09 
82      A1          case1.16     33.35 
1558    A3          case1.16     33.35 

对于每个 ID、名称对,我需要 select 具有最大值的 CaseId。

即我正在寻找以下输出:

Id      Name        CaseId       Value 
82      A1          case1.01     37.71
1558    A3          case1.16     33.35

我尝试了以下方法:

import pandas as pd
pd.pivot_table(df, index=['Id', 'Name'], columns=['CaseId'], values=['Value'], aggfunc=[np.max])['amax']

但它所做的只是为每个 CaseId 列提供最大值,而不是我在上面寻找的结果。

这应该有效:

df = df.sort_values('Value', ascending=False).drop_duplicates('Id').sort_index()

输出:

     Id Name    CaseId  Value
0    82   A1  case1.01  37.71
7  1558   A3  case1.16  33.35

sort_values + drop_duplicates

df.sort_values('Value').drop_duplicates(['Id'],keep='last')
Out[93]: 
     Id Name    CaseId  Value
7  1558   A3  case1.16  33.35
0    82   A1  case1.01  37.71

由于我们 post 同时,添加更多方法

df.sort_values('Value').groupby('Id').tail(1)
Out[98]: 
     Id Name    CaseId  Value
7  1558   A3  case1.16  33.35
0    82   A1  case1.01  37.71

nlargestgroupby

pd.concat(d.nlargest(1, ['Value']) for _, d in df.groupby('Name'))

     Id Name    CaseId  Value
0    82   A1  case1.01  37.71
7  1558   A3  case1.16  33.35

另一个想法是创建一个联合列,取其最大值,然后将其拆分回两列:

df['ValueCase'] = list(zip(df['Value'], df['CaseId']))
p = pd.pivot_table(df, index=['Id', 'Name'], values=['ValueCase'], aggfunc='max')
p['Value'], p['CaseId'] = list(zip(*p['ValueCase']))
del p['ValueCase']

结果:

             CaseId  Value
Id   Name                 
82   A1    case1.01  37.71
1558 A3    case1.16  33.35