Search code examples
pythonpandassortingalphabetical

Pandas sort values alphabetically second character


I currently have a dataframe column that looks like below:

Location
CJ111
CJ111
CD111
CD111
BQ111
BQ111
BL111
BL111

I'm using

df = df.sort_values(by=['Location'], ascending=False)

I want the df to sort by the second character also eg.

Location
CD111
CD111
CJ111
CJ111
BL111
BL111
BQ111
BQ111

Is there anyway to achieve this without using a custom sort key?

Thanks for the help


Solution

  • Use .str[1] to get the second character from the Series, then use argsort to get Positions of values within the sort order, which can be further used to order the original data frame:

    df.loc[df.Location.str[1].argsort()]
    
    #   Location
    #2    CD111
    #3    CD111
    #0    CJ111
    #1    CJ111
    #6    BL111
    #7    BL111
    #4    BQ111
    #5    BQ111