简体   繁体   中英

iterate sort within groupby

I would like to sort this Series within each level of 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

So I get something like

col_0  row_0
a      b        1
       a        2
b      a        3
       b        3
dtype: int64

I tried

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

but I got a cryptic error message.

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

要么:

ctab.sort_index(ascending=[True, False])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM