pandas group by and count, and then sort the full dataframe ascending by group size?

Viewed 52

how do i in pandas do group by and count, and then sort the full dataframe ascending by group size? As an example I have the following dataframe:

        wdate  cls
Found 116 groups
       wdate  cls
0 2020-06-09   84
1 2020-06-09   84
2 2020-06-09  108
3 2020-06-09  108
4 2020-06-08   76
5 2020-06-08   89
6 2020-06-08   93
7 2020-06-08   82
8 2020-06-08   84
9 2020-06-08   89

Which should be sorted like this (smallest group count in the top)

       wdate  cls
4 2020-06-08   76
7 2020-06-08   82
6 2020-06-08   93
5 2020-06-08   89
9 2020-06-08   89
2 2020-06-09  108
3 2020-06-09  108
0 2020-06-09   84
1 2020-06-09   84
8 2020-06-08   84

I cannot figure out how to do that. Thanks

1 Answers

I will do transform count with argsort

df=df.iloc[df.groupby(['cls'])['cls'].transform('count').argsort()]
Out[262]: 
        wdate  cls
4  2020-06-08   76
6  2020-06-08   93
7  2020-06-08   82
2  2020-06-09  108
3  2020-06-09  108
5  2020-06-08   89
9  2020-06-08   89
0  2020-06-09   84
1  2020-06-09   84
8  2020-06-08   84
Related