pandas dataframe group and sort by weekday

You can use ordered catagorical first:

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

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

In pandas 0.21.0+ use:

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

Or reindex:

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

Leave a Comment