我想在 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)
但我收到了一条神秘的错误消息。
最佳答案
ctab.groupby(level=0, group_keys=False).apply(pd.Series.sort_index, ascending=False)
或者:
ctab.sort_index(ascending=[True, False])
关于python - groupby 内迭代排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20039491/