【问题标题】:Using pandas to perform groupby on a dataframe, sort by the count and get the top 2 counts in python使用 pandas 在数据帧上执行 groupby,按计数排序并获取 python 中的前 2 个计数
【发布时间】:2020-01-02 21:47:16
【问题描述】:

我正在处理数据框并希望按列 (ID) 进行分组,显示各自的标签并计算每个标签。然后如何使用 python 获取数据框中每个 ID 的前 2 个标签?

data= 
ID  Label
A   Apple
B   Apple
B   Apple
C   Banana
C   Pear
A   Pear
B   Apple
C   Apple
A   Banana
A   Apple
C   Pear
A   Banana
B   Pear
B   Pear
B   Banana
C   Apple

我已经能够按 ID 和标签进行分组,还可以得到每个 ID 的计数,但我无法得到每个 ID 的前 2 个的最后一部分。

data.groupby(['ID','Label']).size().reset_index(name='counts')

这给了我这张桌子:

ID  Label   counts
A   Apple   2
A   Banana  2
A   Pear    1
B   Apple   3
B   Banana  1
B   Pear    2
C   Apple   2
C   Banana  1
C   Pear    2

我想要的预期结果是:

ID  Label   counts
A   Apple   2
    Banana  2
B   Apple   3
    Pear    2
C   Apple   2
    Pear    2

【问题讨论】:

    标签: pandas sorting pandas-groupby


    【解决方案1】:

    如果你只需要head两个(Top 2)

    data.groupby(['ID']).Label.value_counts().groupby(level=0).head(2)
    Out[770]: 
    ID  Label 
    A   Apple     2
        Banana    2
    B   Apple     3
        Pear      2
    C   Apple     2
        Pear      2
    Name: Label, dtype: int64
    

    【讨论】:

      【解决方案2】:

      使用返回排序值的SeriesGroupBy.value_counts,所以添加了GroupBy.head

      df = (data.groupby('ID')['Label']
                .value_counts()
                .groupby(level=0)
                .head(2)
                .reset_index(name='counts'))
      print (df)
        ID   Label  counts
      0  A   Apple       2
      1  A  Banana       2
      2  B   Apple       3
      3  B    Pear       2
      4  C   Apple       2
      5  C    Pear       2
      

      或者使用自定义 lambda 函数:

      df = (data.groupby('ID')['Label']
                .apply(lambda x: x.value_counts().head(2))
                .reset_index(name='counts'))
      

      【讨论】:

      • 感谢您的回复。如果我想要通过排序而不是使用计数大于 2 的行来获得实际的前 2 名,我会使用什么。
      【解决方案3】:

      pd.concat

      pd.concat({k: d.Label.value_counts().head(2) for k, d in data.groupby('ID')})
      
      A  Apple     2
         Banana    2
      B  Apple     3
         Pear      2
      C  Apple     2
         Pear      2
      Name: Label, dtype: int64
      

      塞住并系好

      pd.concat(
          {k: d.Label.value_counts().head(2) for k, d in data.groupby('ID')},
          names=['ID', 'Label']
      ).reset_index(name='counts')
      
        ID   Label  counts
      0  A   Apple       2
      1  A  Banana       2
      2  B   Apple       3
      3  B    Pear       2
      4  C   Apple       2
      5  C    Pear       2
      

      【讨论】:

        猜你喜欢
        • 2015-10-11
        • 2015-09-16
        • 2013-07-14
        • 2019-09-16
        • 1970-01-01
        • 2020-06-24
        • 1970-01-01
        • 2020-05-09
        相关资源
        最近更新 更多