【问题标题】:Python Pandas groupby and sort along multiple columnsPython Pandas groupby 并沿多列排序
【发布时间】:2022-01-16 18:46:31
【问题描述】:

我在玩 pandas 的 groupby 功能,有一些我无法实现。

我的数据是这样的:

   data = ({
    'Color1':["Blue", "Red", "Green", "Blue", "Red", "Green", "Blue", "Red", "Green"],
    'Color2':["Purple", "Pink", "Yellow", "Purple", "Pink", "Yellow", "Brown", "White", "Grey"],
    'Value':[20, 20, 20, 25, 25, 25, 5, 55, 30]
})

df = pd.DataFrame(data)

我使用 groupby 进行了一些排序(背后的想法是从较大的数据集中提取一些 top N)

df2 = df.groupby(['Color1'], sort=True).sum()[['Value']].reset_index()
df2 = df2.sort_values(by=['Value'], ascending=False)
print(df2)

颜色 1 值 2红100 1 绿色 75 0 蓝色 50

但我最关心的是如何对添加 Color2 进行分组和排序,同时保留 Color 1 上的排序,即结果如下:

  Color1  Color2  Value
0    Red   White     55
1    Red    Pink     45
2  Green  Yellow     45
3  Green    Grey     30
4   Blue  Purple     45
5   Blue   Brown      5

非常感谢您的帮助

【问题讨论】:

    标签: python pandas sorting pandas-groupby


    【解决方案1】:

    试试:

    >>> df.groupby(['Color1', 'Color2']).sum() \
          .sort_values(['Color1', 'Value'], ascending=False).reset_index()
    
      Color1  Color2  Value
    0    Red   White     55
    1    Red    Pink     45
    2  Green  Yellow     45
    3  Green    Grey     30
    4   Blue  Purple     45
    5   Blue   Brown      5
    

    【讨论】:

      【解决方案2】:

      问题是值是字符串,所以sum 加入值而不是求和。

      需要将列转换为数字:

      df = pd.DataFrame(data)
      df['Value'] = df['Value'].astype(int)
      df2 = df.groupby(['Color1','Color2'], sort=False)['Value'].sum().reset_index()
      
      df2 = df2.sort_values(by=['Value'], ascending=False)
      

      如果需要按Color1, Color2Color1 中的原始顺序排序,请使用有序分类:

      vals = df2['Color1'].unique()
      df2['Color1'] = pd.Categorical(df2['Color1'], ordered=True, categories=vals)
      
      df2 = df2.sort_values(['Color1','Color2'])
      print(df2)
      
        Color1  Color2  Value
      1    Red    Pink     45
      4    Red   White     55
      3   Blue   Brown      5
      0   Blue  Purple     45
      5  Green    Grey     30
      2  Green  Yellow     45
      

      【讨论】:

      • 非常感谢,我编辑了原始帖子,因为我无法进行我想要的第二类操作
      • @jezrael。 groupby 中缺少 ]
      • @Bebz - 答案已编辑。
      猜你喜欢
      • 2017-02-07
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      • 1970-01-01
      • 2018-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多