Home > OS >  How to get 00h over/below 23h when ordering
How to get 00h over/below 23h when ordering

Time:12-26

Having this dataframe, what I would is to have the rows that have the start_time with 00:XX:XX at the top (descending for example)

enter image description here

PS: start_time comes from df['start].dt.time

CodePudding user response:

Depending on the exact ordering, use DataFrame.sort_values and possibly Series.str.replace.

  • 00h, 01h, ..., 23h

    Use DataFrame.sort_values which is ascending by default:

    df = df.sort_values('start_time')
    
  • 23h, 22h, ..., 00h

    Use DataFrame.sort_values with ascending=False:

    df = df.sort_values('start_time', ascending=False)
    
  • 00h, 23h, 22h, ..., 01h

    Use Series.str.replace to change 00:##:## into 24:##:##, then DataFrame.sort_values with ascending=False, then change 24:##:## back to 00:##:##:

    df['start_time'] = df['start_time'].str.replace(r'^00(:\d{2}:\d{2})', r'24\1', regex=True)
    df = df.sort_values('start_time', ascending=False)
    df['start_time'] = df['start_time'].str.replace(r'^24(:\d{2}:\d{2})', r'00\1', regex=True)
    
  • Related