给定列表顺序对数据框进行排序

时间:2019-02-26 11:03:22

标签: python pandas sorting

我有一个数据框,其中的行包含人员的名字。 现在我想按名称而不是字母顺序而是给定顺序对数据框进行排序。因此,例如,我想按以下顺序在名称行上排列数据框:

L = ['marc','paul','beck','julia','rest']

如果我有一个数据行,其中包含一行名称,我想让marc在顶部,然后是paul,beck等。

我该如何在python中高效地做到这一点?

2 个答案:

答案 0 :(得分:2)

如果需要按列对数据进行重新排序,请将所有值都转换为ordered categoricals,因此可以使用sort_values

df = pd.DataFrame({'A':['paul','paul','julia','marc','paul','beck','beck','julia']})

L = ['marc','paul','beck','julia','rest']

df['A'] = pd.CategoricalIndex(df['A'], ordered=True, categories=L)

df = df.sort_values('A')
print (df)
       A
3   marc
0   paul
1   paul
4   paul
5   beck
6   beck
2  julia
7  julia

答案 1 :(得分:0)

(function () {
  var element = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  element.setAttribute('viewBox', '5279 1710 12.125 12.125');
  
  var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
  g.setAttribute('transform', 'translate(4311 1165)');
  
  var path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  path.setAttribute('fill', '#000000');
  path.setAttribute('d', 'M346.045,76.5a5.632,5.632,0,0,0,0,8.245,6.143,6.143,0,0,0,1.6-4.122A6');
  path.setAttribute('transform', 'translate(632.48 470.439)');
  
  
  g.appendChild(path);
  element.appendChild(g);
  
  document.querySelector('body').appendChild(element);
})();

这给您:

L = ['marc','paul','beck','julia','rest']
df=pd.DataFrame()
df['L']=L

马克·贝克·贝克,顺序正确。

相关问题