2014-08-28 434 views
2
sample = pd.DataFrame({'Cat':['A','B','C','A','B','C','A','B','C'], 
         'Year':[2001,2002,2003,2001,2002,2003,2001,2002,2003]}) 

for s in sample.groupby(['Year']): 
    print s[0] 

这将使排序GROUPBY列降序

2001 
2002 
2003 

如何按降序排列得到GROUPBY结果进行排序..

2003 
2002 
2001 
+0

@EdChum我得到'类型错误:当我这样做,在我的建议 – richie 2014-08-28 16:47:28

+0

对不起错误,将删除 – EdChum 2014-08-28 16:56:18

回答

2

我认为你最好的选择是将帧提前排序,并将sort=False传递给groupby操作,这样数据就不会被重新排序。

In [78]: sample = sample.sort(['Year'], ascending=False) 

In [79]: for s in sample.groupby(['Year'], sort=False): 
    ...:  print s[0] 
    ...:  
2003 
2002 
2001 
+0

非常感谢。 – richie 2014-08-28 16:58:01