使用Python进行分组和排序
我已经执行了一个按功能分组的操作,我想按时间顺序按月对其进行排序,我如何才能做到这一点?目前,该函数按字母顺序对月份进行排序:使用Python进行分组和排序,python,pandas,sorting,pandas-groupby,Python,Pandas,Sorting,Pandas Groupby,我已经执行了一个按功能分组的操作,我想按时间顺序按月对其进行排序,我如何才能做到这一点?目前,该函数按字母顺序对月份进行排序: func = {'Predictions':['count','mean','median']} table1 = df.groupby(['FLAG','MONTH']).agg(func) 表1 Predictions count mean median FLAG
func = {'Predictions':['count','mean','median']}
table1 = df.groupby(['FLAG','MONTH']).agg(func)
表1
Predictions
count mean median
FLAG MONTH
0 Apr 49812 106.458209 75.325309
Aug 44514 93.718901 74.485782
Feb 51583 98.921119 74.199794
Jan 54837 100.381814 74.682187
Jul 49873 100.621877 73.233328
Jun 47950 103.688532 74.150171
Mar 52816 106.094774 75.104832
May 49404 106.847784 75.844241
Oct 41828 94.744952 76.178077
Sep 41074 96.430351 75.335261
1 Apr 83377 285.631679 144.582569
Aug 66285 217.619038 127.087037
Feb 79693 310.919925 180.507922
Jan 64730 290.113451 137.291571
Jul 105213 298.337893 146.956319
Jun 90305 312.484185 136.222903
Mar 97274 308.013477 165.752471
May 87927 310.162600 142.350688
Oct 47064 258.213619 85.445310
Sep 47337 240.361602 84.597842
谢谢你的帮助 您可以使用:
正如问题中提到的,您可以使用以下代码来获取月份到索引的映射
import calendar
map = {v: k for k,v in enumerate(calendar.month_abbr)}
然后,您可以使用索引映射创建月份索引的新列
#create the new index
df["index"] = df["MONTH"].map(lambda x: map[x])
#groupby the new index
table1 = df.groupby(['FLAG','index']).agg(func).reset_index()
#drop the multi index
table1 = table1.reset_index()
#sort by month
table1.sort_values("index", inplace = True)
太快了。我无法正确复制数据我正在准备df直到现在干杯!我试图将它也应用于同一个表的副本,但没有FLAG变量,出现了以下错误:NotImplementedError:参数级别未为CategoricalIndex实现。reindexoh好的,找到了!再次感谢@jezrael!不客气!如果我的答案有用,别忘了-点击复选标记(
✓答案旁边的代码>),将其从灰显切换为填充。谢谢
#create the new index
df["index"] = df["MONTH"].map(lambda x: map[x])
#groupby the new index
table1 = df.groupby(['FLAG','index']).agg(func).reset_index()
#drop the multi index
table1 = table1.reset_index()
#sort by month
table1.sort_values("index", inplace = True)