【发布时间】: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