【发布时间】:2020-02-22 17:10:20
【问题描述】:
我有一个数据框,我在其中根据两列对数据进行分组,并使用 count 函数进行聚合。现在我希望每个组的计数按排序顺序排列。
>>> df = pd.DataFrame([[1.1, 1.1, 1.1, 2.6, 2.5, 3.4,2.6,2.6,3.4,3.4,2.6,1.1,1.1,3.3], list('AAABBBBABCBDDD'), [1.1, 1.7, 2.5, 2.6, 3.3, 3.8,4.0,4.2,4.3,4.5,4.6,4.7,4.7,4.8], ['x/y/z','x/y/z','x/y/z','x/u','x/u','x/u/v','x/y/z','x','x/u/v/b','-','x/y/z','x','x','x/u/v/w'],['1','3','3','2','4','2','5','3','6','3','5','1','1','1']]).T
>>> df.columns = ['col1','col2','col3','col4','col5']
>>> df1 = df[['col2', 'col1', 'col4']].groupby(['col2', 'col4']).agg('count')
>>> df1
col1
col2 col4
A x 1
x/y/z 3
B x/u 2
x/u/v 1
x/u/v/b 1
x/y/z 2
C - 1
D x 2
x/u/v/w 1
预期输出:
col2 col4 col1
A x/y/z 3
x 1
B x/u 2
x/y/z 2
x/u/v 1
x/u/v/b 1
C - 1
D x 2
x/u/v/w 1
您看到的是每个组的排序顺序。这是我尝试过的。
>>> df1 = df[['col1', 'col2', 'col4']].groupby(['col2', 'col4']).agg('count').sort_index(0, ascending=False)
>>> df1
col1
col2 col4
D x/u/v/w 1
x 2
C - 1
B x/y/z 2
x/u/v/b 1
x/u/v 1
x/u 2
A x/y/z 3
x 1
如何根据计数对组进行排序?
【问题讨论】:
标签: python pandas sorting group-by aggregate