Pandas: grouping and aggregation with multiple functions

前端 未结 4 1718
南笙
南笙 2021-01-14 04:52

Situation

I have a pandas dataframe defined as follows:

import pandas as pd

headers = [\'Group\', \'Element\', \'Case\', \'Score\', \'Evaluation\'         


        
4条回答
  •  一生所求
    2021-01-14 05:09

    Here is possible solution with pd.merge

    >> r = df.groupby('Group') \
    >>       .agg({'Score': 'idxmax', 'Evaluation': 'min'}) \
    >>       .rename(columns={'Score': 'idx'})
    >> for c in ['Score', 'Element', 'Case']:
    >>   r = pd.merge(r, df[[c]], how='left', left_on='idx', right_index=True)
    >> r.drop('Score_idx', axis=1).rename(columns={'Score': 'Max_score_value', 
    >>                                             'Element': 'Max_score_element', 
    >>                                             'Case': 'Max_score_case'})
           Evaluation  Max_score_value  Max_score_element Max_score_case
    Group                                                               
    A            0.41             9.19                  1              y
    B            0.10             9.12                  2              x
    

    Though it provides the desired output, I am not sure about if it's not less efficient than yours approach.

提交回复
热议问题