How to sort pandas dataframe by custom order on string index

前端 未结 3 2041
北恋
北恋 2020-12-15 22:32

I have the following data frame:

import pandas as pd

# Create DataFrame
df = pd.DataFrame(
{\'id\':[2967, 5335, 13950, 6141, 6169],\\
 \'Player\': [\'Cedric         


        
3条回答
  •  时光说笑
    2020-12-15 23:02

    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)

提交回复
热议问题