按组大小对Pandas中分组数据进行排序
我有一个数据集,里面有两列,分别叫做col1和col2。我想根据col1的内容把数据分组,然后再按照每个组的大小进行排序。也就是说,我想把组的大小从小到大显示出来。
我已经写好了分组和显示数据的代码,具体如下:
grouped_data = df.groupby('col1')
"""code for sorting comes here"""
for name,group in grouped_data:
print (name)
print (group)
在显示数据之前,我需要按照组的大小进行排序,但我现在还不知道怎么做。
3 个回答
0
df = pandas.DataFrame([[5, 5], [9, 7], [1, 8], [1, 7], [7, 8], [9, 5], [5, 6], [1, 2], [1, 4], [5, 6]], columns=['A', 'B'])
group = df.groupby('A') count = group.size() count A
grp_len = count[count.index.isin(count.nlargest(2).index)] grp_len A
这是一个表格,里面有两列,分别叫做 A 和 B。每一行代表一个数据点,左边是 A 列的值,右边是 B 列的值。具体的数值如下:
0 行:A 是 0,B 是 5
1 行:A 是 1,B 是 9
2 行:A 是 2,B 是 1
3 行:A 是 3,B 是 1
4 行:A 是 4,B 是 7
5 行:A 是 5,B 是 9
6 行:A 是 6,B 是 5
7 行:A 是 7,B 是 1
8 行:A 是 8,B 是 1
9 行:A 是 9,B 是 5
这是另一组数据,只有两行,分别是:
1 行:A 是 1,B 是 4
2 行:A 是 5,B 是 3
3 行:A 是 7,B 是 1
4 行:A 是 9,B 是 2这些数据的类型是整数(int64),也就是说它们都是数字。
这又是一组数据,和上面类似:
1 行:A 是 1,B 是 4
2 行:A 是 5,B 是 3同样,这些数据的类型也是整数(int64)。
16
你可以使用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)]
注意:作为一个迭代器 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)]
67
对于Pandas版本0.17及以上,可以使用 sort_values
来排序:
df.groupby('col1').size().sort_values(ascending=False)
如果你的版本在0.17之前,可以使用 size().order()
来排序:
df.groupby('col1').size().order(ascending=False)