按照Pandas中的组大小对分组数据进行排序

nis*_*ant 15 python python-3.x pandas pandas-groupby

我的数据集中有两列,col1和col2.我希望按照col1对数据进行分组,然后根据每个组的大小对数据进行排序.也就是说,我想以其大小的升序显示组.

我编写了用于分组和显示数据的代码,如下所示:

grouped_data = df.groupby('col1')
"""code for sorting comes here"""
for name,group in grouped_data:
          print (name)
          print (group)
Run Code Online (Sandbox Code Playgroud)

在显示数据之前,我需要按照组大小对其进行排序,这是我无法做到的.

Vic*_*Yan 41

对于Pandas 0.17+,请使用sort_values:

df.groupby('col1').size().sort_values(ascending=False)
Run Code Online (Sandbox Code Playgroud)

对于0.17之前的版本,您可以使用size().order():

df.groupby('col1').size().order(ascending=False)
Run Code Online (Sandbox Code Playgroud)

  • 我认为这将对mean()值进行排序。我想首先对组进行排序(使用它们的大小),然后找到每个组的平均值。 (2认同)

And*_*den 11

你可以使用python的sort:

In [11]: df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], index=['a', 'b', 'c'], columns=['A', 'B'])

In [12]: g = df.groupby('A')

In [13]: sorted(g,  # iterates pairs of (key, corresponding subDataFrame)
                key=lambda x: len(x[1]),  # sort by number of rows (len of subDataFrame)
                reverse=True)  # reverse the sort i.e. largest first
Out[13]: 
[(1,    A  B
     a  1  2
     b  1  4),
 (5,    A  B
     c  5  6)]
Run Code Online (Sandbox Code Playgroud)

注意:作为迭代器g,迭代密钥对和相应的子帧:

In [14]: list(g)  # happens to be the same as the above...
Out[14]:
[(1,    A  B
     a  1  2
     b  1  4,
 (5,    A  B
     c  5  6)]
Run Code Online (Sandbox Code Playgroud)