pandas 系列按月指数排序 [英] Pandas series sort by month index

查看:50
本文介绍了 pandas 系列按月指数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我想按索引对上述系列的索引列为month的序列进行排序.但是,排序功能不是按月份的日历顺序排序,而是按月份名称的字典顺序排序.如何正确分类以上内容?猜猜我必须指定索引类型为month而不是字符串.任何帮助表示赞赏.下面的代码段.

I'm tring to sort the above series whose index column is month, by month. However instead of sorting by month's calendar order the sort function is sorting by dictionary order of the month name. How can I sort the above correctly? Guess I have to specify that the index type is month and not string. Any help is appreciated. Code snippet below.

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

You can use sorted CategoricalIndex with 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 -但如果缺少某些值,请添加NaNs行:

Or use DataFrame.reindex - but if some value is missing add NaNs rows:

df = df.reindex(cats)

这篇关于 pandas 系列按月指数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆