apply sort to a pandas groupby operation

前端 未结 1 1968
难免孤独
难免孤独 2020-12-06 06:46

How do I apply sort to a pandas groupby operation? The command below returns an error saying that \'bool\' object is not callable

import pandas as pd

df.gro         


        
相关标签:
1条回答
  • 2020-12-06 07:03

    Normally the sort is performed on the groupby keys and as you've found out you can't call sort on a groupby object, what you could do is call apply and pass the DataFrame.sort function and pass the column as the kwarg param:

    In [58]:
    
    df.groupby('cokey').apply(pd.DataFrame.sort, 'A')
    Out[58]:
                   cokey   A    B
    cokey                        
    11168155 1  11168155   0   18
             0  11168155  18   56
             2  11168155  56   96
             3  11168155  96  152
    

    Alternatively you could just sort the df prior to grouping:

    df.sort('A').groupby('cokey')
    

    Update

    For version 0.17.0 and above DataFrame.sort is now deprecated see the docs, one should now use DataFrame.sort_values:

    df.groupby('cokey').apply(pd.DataFrame.sort_values, 'A')
    

    Adding @xgdgsc 's answer in comments to here; in case you need to set ascending flag.

    df.groupby('cokey').apply(pd.DataFrame.sort_values, 'A', ascending=False)
    
    0 讨论(0)
提交回复
热议问题