如何以非标准顺序对pandas中的行进行排序



我有一个pandas数据框架,输入:

df = pd.DataFrame ([['a', 3, 3], ['b', 2, 5], ['c', 4, 9], ['d', 1, 43]], columns = ['col 1' , 'col2', 'col 3'])

或:

  col 1  col2  col 3
0     a     3      3
1     b     2      5
2     c     4      9
3     d     1     43

如果我想按col2排序,我可以用df。Sort,它将升序和降序排序。

然而,如果我想对行进行排序,使col2为:[4,2,1,3],我该怎么做呢?

试试这个:

sortMap = {4:1, 2:2, 1:3,3:4 }
df["new"] = df2['col2'].map(sortMap)
df.sort_values('new', inplace=True)
df
   col1  col2  col3  new
2    c     4     9    1
1    b     2     5    2
3    d     1    43    3
0    a     3     3    4

alt方法创建字典:

ll      = [4, 2, 1, 3] 
sortMap = dict(zip(ll,range(len(ll))))

一种方法是将该列转换为Categorical类型,该类型可以具有任意顺序。

In [51]: df['col2'] = df['col2'].astype('category', categories=[4, 1, 2, 3], ordered=True)
In [52]: df.sort_values('col2')
Out[52]: 
  col 1 col2  col 3
2     c    4      9
3     d    1     43
1     b    2      5
0     a    3      3

备选方案:

In [409]: lst = [4, 2, 1, 3]
In [410]: srt = pd.Series(np.arange(len(lst)), index=lst)
In [411]: srt
Out[411]:
4    0
2    1
1    2
3    3
dtype: int32
In [412]: df.assign(x=df.col2.map(srt))
Out[412]:
  col 1  col2  col 3  x
0     a     3      3  3
1     b     2      5  1
2     c     4      9  0
3     d     1     43  2
In [413]: df.assign(x=df.col2.map(srt)).sort_values('x')
Out[413]:
  col 1  col2  col 3  x
2     c     4      9  0
1     b     2      5  1
3     d     1     43  2
0     a     3      3  3
In [414]: df.assign(x=df.col2.map(srt)).sort_values('x').drop('x',1)
Out[414]:
  col 1  col2  col 3
2     c     4      9
1     b     2      5
3     d     1     43
0     a     3      3

注意:我确实更喜欢@chrisb的解决方案-它更优雅,可能会更快

最新更新