Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

python - apply sort to a pandas groupby operation

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.groupby('cokey').sort('A')

cokey       A   B
11168155    18  56
11168155    0   18
11168155    56  96
11168156    96  152
11168156    0   96
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...