熊猫系列排序月份指数
问题描述:
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
:
df.index = pd.CategoricalIndex(df.index,
categories=['Jan', 'Feb', 'Mar', 'Apr','May','Jun', 'Jul', 'Aug','Sep', 'Oct', 'Nov', 'Dec'],
sorted=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
答
没事,不是很复杂。我确定Categorical只能用Categorical解决问题。 我所做的是 -
- 排序一个月,而月均被表示为整数
- 为由此带来的一系列应用在指数映射到整数月转换为字符串缩写
我相信有更有效的方法来解决这个问题,所以如果你有更好的方法,请张贴相同的。
import calendar
months = release_dates[release_dates.title.str.contains('Christmas') & (release_dates.country=='USA')].date.dt.month
counts = months.value_counts()
counts.sort_index(inplace=True)
counts.index = map(lambda x: calendar.month_abbr[x], counts.index)
counts.plot.bar()
C:\ python的3.5 \ LIB \站点包\大熊猫\指标\ category.py:128:RuntimeWarning:价值观和类别有不同的dtypes。您是否想要使用 'Categorical.from_codes(代码,类别)'? 数据=范畴(数据,类别=类别有序有序=) C:\蟒3.5 \ lib中\站点包\大熊猫\索引\ category.py:128:RuntimeWarning:类别都不在值被发现了。您的意思是使用 “Categorical.from_codes(代码,类别)”? 数据=分类(数据,类别=类别,下令=下令 – lalatnayak
我想你可以试试。 – jezrael
什么是你的大熊猫版本? – jezrael