我的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。 ?
答案 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)