代码之家  ›  专栏  ›  技术社区  ›  Claudiu Creanga

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

  •  2
  • Claudiu Creanga  · 技术社区  · 7 年前

    使用此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']
    

    我知道这里的答案: sorting by a custom list in pandas

    它提供了这个解决方案:

    df.Tm = df.Tm.astype("category")
    df.Tm.cat.set_categories(sorter, inplace=True)
    
    df.sort_values(["Tm"]) 
    

    但是,这个答案是4年前的,并且列中没有出现在分拣机中的值是 换成了奶奶(我不想要) . 我知道我可能会用。 unique() 并附加到列表的末尾。

    因此,我的问题是:今天有没有更好的方法通过使用熊猫新的内置功能来进行自定义排序,如果要将所有值保留在一个列中,而不是用nan替换它们,有没有比以下更好的解决方案:

    other_values = set(df["TM"].unique()) - set(sorter)
    sorter.append(other_values)
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   jpp    7 年前

    你提到的解决方案是一个很好的起点。你可以使用 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