如何按一列分组并排序另一列的值? [英] How to group by one column and sort the values of another column?
本文介绍了如何按一列分组并排序另一列的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的数据框
import pandas as pd
df = pd.DataFrame({'A': ['one', 'one', 'two', 'two', 'one'] ,
'B': ['Ar', 'Br', 'Cr', 'Ar','Ar'] ,
'C': ['12/15/2011', '11/11/2001', '08/30/2015', '07/3/1999','03/03/2000' ],
'D':[1,7,3,4,5]})
我的目标是按列A
分组,并按列B
在分组的结果内排序.
My goal is to group by column A
and sort within grouped results by column B
.
这是我想出的:
sort_group = df.sort_values('B').groupby('A')
我希望分组操作不会扭曲顺序,但是它不起作用,也不会返回数据帧,而是返回groupby
对象
I was hoping that grouping operation would not distort order, but it does not work and also returns not a dataframe, but groupby
object
<pandas.core.groupby.DataFrameGroupBy object at 0x0000000008B190B8>
有什么建议吗?
推荐答案
您不能将sort_values
直接应用于groupby
对象,但是需要apply
:
You cannot apply sort_values
directly to a groupby
object but you need an apply
:
df.groupby('A').apply(lambda x: x.sort_values('B'))
为您提供所需的输出:
A B C D
A
one 0 one Ar 12/15/2011 1
4 one Ar 03/03/2000 5
1 one Br 11/11/2001 7
two 3 two Ar 07/3/1999 4
2 two Cr 08/30/2015 3
这篇关于如何按一列分组并排序另一列的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文