Sort Python DataFrame by Day of the Week
Question: I'm trying to sort my dataframe by the day of the week in the index. I was
able to create a workaround where I created an additional column that I
manually assigned the correct order value to and then sorted. But there has to
be a better way, especially when I'm dealing with potentially more date
values.

    
    
    dict = {'Monday': Monday/MonCount, 'Tuesday': Tuesday/TueCount, 'Wednesday': Wednesday/WedCount, 'Thursday': Thursday/ThuCount, 'Friday': Friday/FriCount}
    df = pd.Series(dict, name='DailyValue')
    dff = DataFrame(df)
    dff['Day'] = dff.index
    dff['Sorter'] = [5,1,4,2,3]
    
    dff.sort_values(by = ['Sorter'], inplace = True) 
    #dff.sort(['Day'], ascending = True) 
    
    dff.plot(kind='bar', grid = True, y = ['DailyValue'])
    plt.show()
    


Answer: You can use a list comprehension to generate the weekdays (i.e. 0-6) in your
index, and then create a series from these values. You sort this series by
these weekday values and take the index. You then use `ix` to index your
original series based on this sorted index.

    
    
    import numpy as np
    import pandas as pd
    
    s = pd.Series(np.random.randn(14), index=pd.date_range('2016-1-1', periods=14))
    
    s
    Out[34]: 
    2016-01-01    0.915488
    2016-01-02   -1.053409
    2016-01-03   -1.826033
    2016-01-04    0.559250
    2016-01-05   -0.278086
    2016-01-06    0.041113
    2016-01-07    1.076463
    2016-01-08    0.942720
    2016-01-09   -0.850388
    2016-01-10   -0.649713
    2016-01-11    2.769957
    2016-01-12    0.498103
    2016-01-13    1.098085
    2016-01-14    0.699077
    Freq: D, dtype: float64
    
    idx = pd.Series([d.weekday() for d in s.index]).sort_values().index
    
    s.ix[idx]
    Out[36]: 
    2016-01-04    0.559250
    2016-01-11    2.769957
    2016-01-05   -0.278086
    2016-01-12    0.498103
    2016-01-06    0.041113
    2016-01-13    1.098085
    2016-01-07    1.076463
    2016-01-14    0.699077
    2016-01-01    0.915488
    2016-01-08    0.942720
    2016-01-02   -1.053409
    2016-01-09   -0.850388
    2016-01-03   -1.826033
    2016-01-10   -0.649713
    dtype: float64
    

As a one liner...

    
    
    s_new = s.ix[pd.Series([d.weekday() for d in s.index]).sort_values().index]
    

Exactly the same for a dataframe.

    
    
    df_new = df.ix[pd.Series([d.weekday() for d in df.index]).sort_values().index]
    

