pandas 熊猫数据框分组并按工作日排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47741400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:52:38  来源:igfitidea点击:

pandas dataframe group and sort by weekday

pandasdataframe

提问by Nour

I have pandas DataFrame that includes Day of Weekcolumn.

我有包含Day of Week列的Pandas DataFrame 。

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

plot the DataFrame displays 'Day of Week' in alphabetical order: 'Friday', 'Monday', 'Saturday', 'Sunday' , 'Tuesday' , 'Thursday', 'Wednesday'.

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

how can i sort and display df_weekday in proper weekday order 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'. ?

我如何按正确的工作日顺序对 df_weekday 进行排序和显示'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'。?

回答by jezrael

You can use ordered catagoricalfirst:

您可以先使用有序分类

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:

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)

Or reindex:

reindex

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