在groupby中迭代排序

时间:2013-11-18 03:18:19

标签: python sorting group-by pandas

我想在col_0

的每个级别中对此系列进行排序
import pandas as pd
a = 'a b b a a a a b b'.split()
b = 'b a b b b a a b b'.split()
aS = pd.Series(a)
bS = pd.Series(b)
ctab = pd.crosstab(aS,bS).unstack()

In[2]: ctab

Out[2]:
col_0  row_0
a      a        2
       b        1
b      a        3
       b        3
dtype: int64

所以我得到像

这样的东西
col_0  row_0
a      b        1
       a        2
b      a        3
       b        3
dtype: int64

我试过

ctab.groupby(level=0).sort(ascending=False)

但是我收到了一个神秘的错误消息。

1 个答案:

答案 0 :(得分:3)

ctab.groupby(level=0, group_keys=False).apply(pd.Series.sort_index, ascending=False)

或:

ctab.sort_index(ascending=[True, False])
相关问题