pandas python sort groupby data by key/function

ar7v8xwq  于 11个月前  发布在  Python
关注(0)|答案(3)|浏览(123)

我想排序的数据,但不是按月份顺序,而不是按月份顺序,即第一次销售1月,然后2月等,见我创建的数据说明

month=['January','February','March','April','January','February','March','April']
sales=[10,100,130,145,13409,670,560,40]
dict = {'month': month, 'sales': sales}  
df = pd.DataFrame(dict)
df.groupby('month')['sales'].mean().sort_values()

字符串
在这种情况下,我收到的数据的销售平均,但我想排序的价值按月份顺序

vltsax25

vltsax251#

在排序之前,将其更改为分类:

months = ['January', 'February','March','April']
df['month'] = pd.Categorical(df['month'],categories=months,ordered=True)
df.sort_values(by=['month'], ascending=True, inplace=True)

字符串
输出为:

month  sales
0   January     10
4   January  13409
1  February    100
5  February    670
2     March    130
6     March    560
3     April    145
7     April     40

7uzetpgm

7uzetpgm2#

您可以使用下面的代码对月明细按升序排序,而销售明细按降序表示。

months = ['January', 'February','March','April']
df['month'] = pd.Categorical(df['month'],categories=months,ordered=True)
df.sort_values(['month', 'sales'], ascending=[True, False])

字符串
请访问此link以获取更多参考。

btxsgosb

btxsgosb3#

或者,可能更慢,但只是为了后代,你可以使用lambda与map:

month_order = {"January": 1, "February": 2, "March": 3, "April": 4}

df = df.sort_values(by="month", key=lambda x: x.map(month_order), ignore_index=True)

字符串

相关问题