按pandas中的自定义列表排序

itj*_*s18 44 python sorting pandas

阅读完:http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.sort.html

我似乎还无法弄清楚如何通过自定义列表对列进行排序.显然,默认排序是按字母顺序排列的.我举个例子.这是我的(非常删节)数据框:

             Player      Year   Age   Tm     G
2967     Cedric Hunter   1991    27  CHH     6
5335     Maurice Baker   2004    25  VAN     7
13950    Ratko Varda     2001    22  TOT     60
6141     Ryan Bowen      2009    34  OKC     52
6169     Adrian Caldwell 1997    31  DAL     81
Run Code Online (Sandbox Code Playgroud)

我希望能够按Player,Year和Tm进行排序.按正常顺序,播放器和年份的默认排序对我来说没问题.但是,我不希望团队按字母顺序排序b/c我希望TOT始终位于顶部.

这是我创建的列表:

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']
Run Code Online (Sandbox Code Playgroud)

阅读完上面的链接后,我认为这样可行,但事实并非如此:

df.sort(['Player', 'Year', 'Tm'], ascending = [True, True, sorter])
Run Code Online (Sandbox Code Playgroud)

它仍然在顶部有ATL,这意味着它按字母顺序排序,而不是根据我的自定义列表.任何帮助真的会非常感激,我只是想不出来.

dme*_*meu 59

我刚刚发现使用pandas 15.1可以使用分类系列(http://pandas.pydata.org/pandas-docs/stable/10min.html#categoricals)

至于您的示例,我们定义相同的数据框架和分拣机:

import pandas as pd

data = {
    '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]
}

# Create DataFrame
df = pd.DataFrame(data)

# Define the sorter
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']
Run Code Online (Sandbox Code Playgroud)

使用数据框架和分拣机(类别订单),我们可以在pandas 15.1中执行以下操作:

# Convert Tm-column to category and in set the sorter as categories hierarchy
# Youc could also do both lines in one just appending the cat.set_categories()
df.Tm = df.Tm.astype("category")
df.Tm.cat.set_categories(sorter, inplace=True)

print(df.Tm)
Out[48]: 
0    CHH
1    VAN
2    TOT
3    OKC
4    DAL
Name: Tm, dtype: category
Categories (38, object): [TOT < ATL < BOS < BRK ... UTA < VAN < WAS < WSB]

df.sort_values(["Tm"])  ## 'sort' changed to 'sort_values'
Out[49]: 
   Age   G           Player   Tm  Year     id
2   22  60      Ratko Varda  TOT  2001  13950
0   27   6    Cedric Hunter  CHH  1991   2967
4   31  81  Adrian Caldwell  DAL  1997   6169
3   34  52       Ryan Bowen  OKC  2009   6141
1   25   7    Maurice Baker  VAN  2004   5335
Run Code Online (Sandbox Code Playgroud)

  • @fabiofili2pi - inplace=True 已被弃用 `df.Tm = f.Tm.cat.set_categories(sorter)` 现在将是正确的语法 (2认同)

Mar*_*ius 31

从版本 1.1.0 开始,您可以使用该key属性对值进行排序:

df.sort_values(by="Tm", key=lambda column: column.map(lambda e: sorter.index(e)), inplace=True)
Run Code Online (Sandbox Code Playgroud)

  • 很好的一个,谢谢!我从我的(旧)答案中引用了你的答案。现在这是更好的选择。 (4认同)

Gui*_*not 25

下面是一个对数据帧执行字典排序的示例.我们的想法是根据特定的排序创建一个数字索引.然后根据索引执行数字排序.将一列添加到数据框中,然后将其删除.

import pandas as pd

# Create DataFrame
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' ,'DAL'],\
 'G':[6 ,7 ,60 ,52 ,81]})

# Define the sorter
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']

# Create the dictionary that defines the order for sorting
sorterIndex = dict(zip(sorter,range(len(sorter))))

# Generate a rank column that will be used to sort
# the dataframe numerically
df['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)
Run Code Online (Sandbox Code Playgroud)


Arl*_*leg 11

根据pandas 1.1.0 文档,可以key像在sorted函数中一样使用参数进行排序(终于!)。在这里我们如何排序Tm

import pandas as pd


data = {
    '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]
}

# Create DataFrame
df = pd.DataFrame(data)


def tm_sorter(column):
    """Sort function"""
    teams = ['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']
    correspondence = {team: order for order, team in enumerate(teams)}
    return column.map(correspondence)

df.sort_values(by='Tm', key=tm_sorter)
Run Code Online (Sandbox Code Playgroud)

可悲的是,看起来我们只能在按 1 列排序时使用此功能(带keys 的列表是不可接受的)。可以通过以下方式规避groupby

df.sort_values(['Player', 'Year']) \
  .groupby(['Player', 'Year']) \
  .apply(lambda x: x.sort_values(by='Tm', key=tm_sorter)) \
  .reset_index(drop=True)
Run Code Online (Sandbox Code Playgroud)

如果您知道如何keysort_values多列中使用,请告诉我

  • 为了澄清,您仍然可以按多列对数据帧进行排序(即`df.sort_values(by=['col1', 'col2'], key=mysort)`),但`key`函数只会在a处接收一列时间。我想如果您的关键函数是内联的,您可以访问完整的数据框对象,例如,您希望一列根据与另一列的比较进行排序。我喜欢你使用“map”的解决方案,但想注意同样可以用“cat = pd.Categorical(column,categories=teams,ordered=True)”然后“return pd.Series(cat)”来完成。 (2认同)

ALo*_*llz 9

DataFrame.loc当您需要按单个自定义列表进行排序时,设置索引非常有用。因为loc将为不在 DataFrame 中的NaN值创建行,sorter我们将首先找到交集。这可以防止任何不需要的向上转换。任何值不在列表中的行都将被删除。

true_sort = [s for s in sorter if s in df.Tm.unique()]
df = df.set_index('Tm').loc[true_sort].reset_index()

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

起始数据:

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

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']
Run Code Online (Sandbox Code Playgroud)


kai*_*kai 9

df1 = df.set_index('Tm')
df1.loc[sorter]
Run Code Online (Sandbox Code Playgroud)

  • 这应该是公认的答案 (3认同)

小智 9

这只需几行即可完成工作

# Create a dummy df with the required list and the col name to sort on
dummy = pd.Series(sort_list, name = col_name).to_frame()

# Use left merge on the dummy to return a sorted df
sorted_df = pd.merge(dummy, df, on = col_name, how = 'left')
Run Code Online (Sandbox Code Playgroud)