简体   繁体   English

Python Pandas 分组并沿多列排序

[英]Python Pandas groupby and sort along multiple columns

I was playing with pandas groupby function, and there is something I can't manage to achieve.我正在玩 pandas groupby function,但有些事情我无法实现。

My data is like:我的数据是这样的:

   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)

I used the groupby to do some sorting (the idea behind is to extract some top N from larger datasets)我使用 groupby 进行了一些排序(背后的想法是从较大的数据集中提取一些 top N)

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

Color1 Value 2 Red 100 1 Green 75 0 Blue 50颜色 1 值 2 红色 100 1 绿色 75 0 蓝色 50

But my biggest concern is how to groupby and sort adding Color2 while preserving the sort on Color 1 ie a result such as:但我最关心的是如何对添加 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

Thanks a lot for your help非常感谢你的帮助

Problem is values are strings, so sum join values instead summing.问题是值是字符串,所以sum连接值而不是求和。

Need convert column to numeric:需要将列转换为数字:

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)

If need sorting by Color1, Color2 with original order in Color1 use ordered Categoricals:如果需要按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

Try:尝试:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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