Skip to content Skip to sidebar Skip to footer

How To Sort Pandas Dataframe By Custom Order On String Index

I have the following data frame: import pandas as pd # Create DataFrame df = pd.DataFrame( {'id':[2967, 5335, 13950, 6141, 6169],\ 'Player': ['Cedric Hunter', 'Maurice Baker' ,\

Solution 1:

Just reindex

df.reindex(reorderlist)Out[89]:AgeGTmYearidPlayerMauriceBaker257VAN2004   5335AdrianCaldwell3181DAL1997   6169RatkoVarda2260TOT2001  13950RyanBowen3452OKC2009   6141CedricHunter276CHH1991   2967

Solution 2:

As of Pandas 1.1 DataFrame.sort_values has a key param that takes a callable to control sorting. So you could use an approach like the following:

defsorter(column):
    reorder = [
        "Maurice Baker",
        "Adrian Caldwell",
        "Ratko Varda",
        "Ryan Bowen",
        "Cedric Hunter",
    ]
    # This also works:# mapper = {name: order for order, name in enumerate(reorder)}# return column.map(mapper)
    cat = pd.Categorical(column, categories=reorder, ordered=True)
    return pd.Series(cat)

df_sorted = df.sort_values(by="Player", key=sorter)

There may be some practical differences between using pd.Categorical and the column.map alternative I put in the comments. For example, see these caveats. I'm showing both for completeness. I also haven't tested how this compares performance-wise to the current accepted solution that uses df.reindex. The best approach might be different when you have a MultiIndex in play too.

Solution 3:

To get a custom sort-order on your list of strings, declare it as a categorical and manually specify that order in a sort:

player_order = pd.Categorical([ 'Maurice Baker', 'Adrian Caldwell','Ratko Varda' ,'Ryan Bowen' ,'Cedric Hunter'],
              ordered=True)

This is since pandas does not yet allow Categoricals as indices: df.set_index(keys=player_order, inplace=True)TypeError: unhashable type: 'Categorical'

So you'll want to do a manual custom sort using df.sort_index(level=player_order)

Post a Comment for "How To Sort Pandas Dataframe By Custom Order On String Index"