pandas dataframe group and sort by weekday

前端 未结 1 1826
终归单人心
终归单人心 2020-12-11 07:54

I have pandas DataFrame that includes Day of Week column.

df_weekday = df.groupby([\'Day of Week\']).sum()
df_weekday[[\'Spent\', \'Clicks\', \'         


        
相关标签:
1条回答
  • 2020-12-11 08:17

    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) 
    
    0 讨论(0)
提交回复
热议问题