pandas数据帧组并按工作日排序

时间:2017-12-10 17:19:49

标签: pandas dataframe

我的pandas DataFrame包含Day of Week列。

df_weekday = df.groupby(['Day of Week']).sum()
df_weekday[['Spent', 'Clicks', 'Impressions']].plot(figsize=(16,6), subplots=True);

绘制DataFrame显示'星期几'按字母顺序排列:'Friday', 'Monday', 'Saturday', 'Sunday' , 'Tuesday' , 'Thursday', 'Wednesday'

如何在正确的工作日订单'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'中排序和显示df_weekday。 ?

1 个答案:

答案 0 :(得分:3)

您可以先使用ordered catagorical

cats = [ 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

df['Day of Week'] = df['Day of Week'].astype('category', categories=cats, ordered=True)

pandas 0.21.0+中使用:

from pandas.api.types import CategoricalDtype
cat_type = CategoricalDtype(categories=cats, ordered=True)
df['Day of Week'] = df['Day of Week'].astype(cat_type)

reindex

df_weekday = df.groupby(['Day of Week']).sum().reindex(cats)