按照自定义值列表对pandas df列进行排序

3

我想使用这个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)

2
我认为你提供的解决方案听起来很合理,可能是你能做到的最好的。虽然看起来你可能想在第一行交换你的集合:set(df["TM"].unique()) - set(sorter)。但我不排除其他可能性。也许会有其他人提出不同的解决方案 :) - busybear
1个回答

4
你提到的解决方案是一个不错的起点。你可以使用 ordered=True 以及 set_categories 来确保按照需要设置分类顺序:
df['Tm'] = df['Tm'].astype('category')
not_in_list = df['Tm'].cat.categories.difference(sorter)
df['Tm'] = df['Tm'].cat.set_categories(np.hstack((sorter, not_in_list)), ordered=True)

df = df.sort_values('Tm')

print(df)

   Age   G           Player                           Tm  Year     id
2   22  60      Ratko Varda                          TOT  2001  13950
0   27   6    Cedric Hunter                          CHH  1991   2967
3   34  52       Ryan Bowen                          OKC  2009   6141
1   25   7    Maurice Baker                          VAN  2004   5335
4   31  81  Adrian Caldwell  value_not_present_in_sorter  1997   6169

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接