下面是对数据框执行字典排序的示例。这个想法是基于特定的排序创建一个数字索引。然后根据索引执行数字排序。为此,将一列添加到数据框中,然后将其删除。
import pandas as pd# Create Dataframedf = pd.Dataframe({'id':[2967, 5335, 13950, 6141, 6169], 'Player': ['Cedric Hunter', 'Maurice Baker', 'Ratko Varda' ,'Ryan Bowen' ,'Adrian Caldwell'], 'Year': [1991, 2004, 2001, 2009, 1997], 'Age': [27, 25, 22, 34, 31], 'Tm': ['CHH' ,'VAN' ,'TOT' ,'OKC', 'DAL'], 'G': [6, 7, 60, 52, 81]})# Define the sortersorter = ['TOT', 'ATL', 'BOS', 'BRK', 'CHA', 'CHH', 'CHI', 'CLE', 'DAL','DEN', 'DET', 'GSW', 'HOU', 'IND', 'LAC', 'LAL', 'MEM', 'MIA', 'MIL', 'MIN', 'NJN', 'NOH', 'NOK', 'NOP', 'NYK', 'OKC', 'ORL', 'PHI', 'PHO', 'POR', 'SAC', 'SAS', 'SEA', 'TOR', 'UTA', 'VAN', 'WAS', 'WSB']# Create the dictionary that defines the order for sortingsorterIndex = dict(zip(sorter, range(len(sorter))))# Generate a rank column that will be used to sort# the dataframe numericallydf['Tm_Rank'] = df['Tm'].map(sorterIndex)# Here is the result asked with the lexicographic sort# Result may be hard to analyze, so a second sorting is# proposed next## NOTE: ## Newer versions of pandas use 'sort_values' instead of 'sort'df.sort_values(['Player', 'Year', 'Tm_Rank'], ascending = [True, True, True], inplace = True)df.drop('Tm_Rank', 1, inplace = True)print(df)# Here is an example where 'Tm' is sorted first, that will # give the first row of the Dataframe df to contain TOT as 'Tm'df['Tm_Rank'] = df['Tm'].map(sorterIndex)## NOTE: ## Newer versions of pandas use 'sort_values' instead of 'sort'df.sort_values(['Tm_Rank', 'Player', 'Year'], ascending = [True , True, True], inplace = True)df.drop('Tm_Rank', 1, inplace = True)print(df)


