我想使用这个df按照自定义列表对一列进行排序:
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' ,'value_not_present_in_sorter'],\
'G':[6 ,7 ,60 ,52 ,81]})
Age G Player Tm Year id
0 27 6 Cedric Hunter CHH 1991 2967
1 25 7 Maurice Baker VAN 2004 5335
2 22 60 Ratko Varda TOT 2001 13950
3 34 52 Ryan Bowen OKC 2009 6141
4 31 81 Adrian Caldwell value_not_present_in_sorter 1997 6169
假设这是自定义列表:
sorter = ['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']
我知道这里的答案:在Pandas中按自定义列表排序。
该解决方案如下:
df.Tm = df.Tm.astype("category")
df.Tm.cat.set_categories(sorter, inplace=True)
df.sort_values(["Tm"])
但是那个答案已经是4年前的了,列中的值如果不在排序器中,则被替换为NaN(我不想要)。我知道我可能可以使用unique()
并将其附加到列表末尾。
所以我的问题是:今天是否有更好的方法来使用pandas新内置的功能进行自定义排序?如果要保留列中的所有值而不替换它们为NaN,则是否有更好的解决方案:
other_values = set(df["TM"].unique()) - set(sorter)
sorter.append(other_values)
set(df["TM"].unique()) - set(sorter)
。但我不排除其他可能性。也许会有其他人提出不同的解决方案 :) - busybear