【问题标题】:pandas group by and count, and then sort the full dataframe ascending by group size?熊猫分组并计数,然后按组大小升序对完整数据框进行排序?
【发布时间】:2020-06-12 20:05:38
【问题描述】:

我如何在 pandas 中进行分组和计数,然后按组大小升序对完整数据框进行排序? 例如,我有以下数据框:

        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

应该这样排序(最小的组数在顶部)

       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

我不知道该怎么做。 谢谢

【问题讨论】:

    标签: python-3.x pandas numpy


    【解决方案1】:

    我会和argsort一起transformcount

    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
    

    【讨论】:

      猜你喜欢
      • 2017-10-12
      • 1970-01-01
      • 2018-05-24
      • 2019-04-12
      • 2021-05-17
      • 2019-07-05
      • 2021-08-08
      • 1970-01-01
      • 2021-09-15
      相关资源
      最近更新 更多