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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22291395/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:48:00  来源:igfitidea点击:

Sorting the grouped data as per group size in Pandas

pythonpython-3.xpandaspandas-groupby

提问by nishant

I have two columns in my dataset, col1 and col2. I want group the data as per col1 and then sort the data as per the size of each group. That is, I want to display groups in ascending order of their size.

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

I have written the code for grouping and displaying the data as follows:

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

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

Before displaying the data, I need to sort it as per group size, which I am not able to do.

在显示数据之前,我需要根据组大小对其进行排序,但我无法做到。

回答by Victor Yan

For Pandas 0.17+, use sort_values:

对于 Pandas 0.17+,使用sort_values

df.groupby('col1').size().sort_values(ascending=False)

For pre-0.17, you can use size().order():

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

df.groupby('col1').size().order(ascending=False)

回答by Andy Hayden

You can use python's sorted:

您可以使用 python 的sorted

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)]

Note: as an iterator g, iterates over pairs of the key and the corresponding subframe:

注意:作为迭代器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)]

回答by srishti k

import pandas as pd

df = pd.DataFrame([[5,5],[9,7],[1,8],[1,7,],[7,8],[9,5],[5,6],[1, 2], [1, 4], [5, 6]], columns=['A', 'B'])

  A   B  
0   5   5  
1   9   7  
2   1   8  
3   1   7  
4   7   8  
5   9   5  
6   5   6  
7   1   2  
8   1   4  
9   5   6    

group = df.groupby('A')

count = group.size()

count  
A  

1   4  
5   3  
7   1  
9   2    
dtype: int64

grp_len = count[count.index.isin(count.nlargest(2).index)]

grp_len   
A  
1   4  
5   3  
dtype: int64