Pandas对数据帧进行分组和排序

时间:2017-12-27 11:05:26

标签: python pandas

我有以下数据框:

A   B
b   d
b   d
b   d
b   e
a   f
a   f
c   g
c   h

使用代码

tables_df=df.groupby(['A','B'], as_index=False)['count'].sum().sort_values(by='count', ascending=False)

我可以分组和排序为

A   B   count
b   d   3
a   f   2
b   e   1
c   g   1
c   h   1

但是,我希望对其进行分组,并根据A列的计数按降序排序:

A   B   count
b   d   3
b   e   1
a   f   2
c   g   1
c   h   1

我该怎么做?

为了进一步说明,值应该仅根据列A的计数按降序排序,但是它应该根据两列对值进行分组。 (在这种情况下,因为b具有最高的总计数,所以它应该在列表的顶部,并且a具有第二高的计数,因此应该低于b,即使计数低于af应该高于af,因为b具有整体数量较高)。

0 个答案:

没有答案