【问题标题】:Pandas pivot table selecting rows with maximum values熊猫数据透视表选择具有最大值的行
【发布时间】:2018-10-31 06:49:12
【问题描述】:

我有熊猫数据框:

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、Name 对,我需要选择具有最大值的 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 作为列,它给出了最大值,而不是我在上面寻求的结果。

【问题讨论】:

    标签: pandas python-3.5


    【解决方案1】:

    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
    

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

    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
    

    【讨论】:

    • 不错的选择,+1
    【解决方案2】:

    这应该可行:

    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
    

    【讨论】:

      【解决方案3】:

      使用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
      

      【讨论】:

        【解决方案4】:

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

        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
        

        【讨论】:

          猜你喜欢
          • 2019-02-12
          • 1970-01-01
          • 1970-01-01
          • 2021-02-28
          • 2023-01-11
          • 1970-01-01
          • 2020-09-09
          • 1970-01-01
          相关资源
          最近更新 更多