Python 将排序应用于 Pandas groupby 操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29479357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
apply sort to a pandas groupby operation
提问by user308827
How do I apply sort to a pandas groupby operation? The command below returns an error saying that 'bool' object is not callable
如何将排序应用于 Pandas groupby 操作?下面的命令返回一个错误,指出“bool”对象不可调用
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
采纳答案by EdChum
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:
通常排序是在 groupby 键上执行的,正如您发现不能调用sort
groupby 对象一样,您可以做的是调用apply
并传递DataFrame.sort
函数并将列作为 kwarg 参数传递:
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 进行排序:
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
:
对于现在已弃用的版本0.17.0
及更高版本,DataFrame.sort
请参阅文档,现在应该使用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.
在此处的评论中添加 @xgdgsc 的答案;如果您需要设置升序标志。
df.groupby('cokey').apply(pd.DataFrame.sort_values, 'A', ascending=False)