Dec 47
Nov 36
Oct 14
Sep 2
Jan 2
Aug 2
May 1
Apr 1
Jun 1
Jul 1
Feb 1
Name: date, dtype: int64
我想按月对索引列为月的上述系列进行排序。但是,排序函数不是按月份的日历顺序排序,而是按月份名称的字典顺序排序。如何正确排序以上内容?猜猜我必须指定索引类型是月份而不是字符串。任何帮助表示赞赏。下面的代码片段。
import calendar
movies = release_dates[release_dates.title.str.contains('Christmas') & (release_dates.country=='USA')]
movies = movies.date.dt.month.apply(lambda x: calendar.month_abbr[x])
counts = movies.value_counts()
counts
最佳答案
您可以使用已排序的 CategoricalIndex
与 sort_index
:
cats = ['Jan', 'Feb', 'Mar', 'Apr','May','Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov', 'Dec']
df.index = pd.CategoricalIndex(df.index, categories=cats, ordered=True)
df = df.sort_index()
print (df)
date
Jan 2
Feb 1
Apr 1
May 1
Jun 1
Jul 1
Aug 2
Sep 2
Oct 14
Nov 36
Dec 47
或者使用DataFrame.reindex
- 但如果缺少某些值,请添加 NaN 行:
df = df.reindex(cats)
关于python - Pandas 系列按月份索引排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40816144/