Apply sort to pandas groupby operation

How to apply sorting to pandas groupby operation? The command below returns an error indicating that the "bool" object cannot be called

import pandas as pd

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

cokey       A   B
11168155    18  56
11168155    0   18
11168155    56  96
11168156    96  152
11168156    0   96
+4
source share
1 answer

Usually sorting is performed on the groupby keys, and, as you found out, you cannot call sortthe groupby object, then you can make a call applyand pass a function DataFrame.sortand pass the column as the kwarg parameter:

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 can just sort the df before grouping:

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

Update

0.17.0 DataFrame.sort , . docs, DataFrame.sort_values:

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

All Articles