首页 > 解决方案 > 特殊排序列数据框

问题描述

我有下面的数据框。

 d = {'id': ['x1', 'x2','x3','x4','x5','x6','x7'],'t1': [3,11,4,4,10,16,8],'t2':[20,14,4,15,22,11,4], 
 't3':[14,2,12,18,16,16,11]}
  df = pd.DataFrame(data=d)

我想在 t1 上添加包含排序的列,然后如果两行的 t1 相等,那么我们可以查看 t2 并做同样的事情。我的专栏将包含。

df['calculated'] =[7,2,6,5,3,1,4]

我的预期数据框将是:

 d = {'id': ['x1', 'x2','x3','x4','x5','x6','x7'],'t1': [3,11,4,4,10,16,8],'t2':[20,14,4,15,22,11,4], 
 't3':[14,2,12,18,16,16,11],'calculated':[7,2,6,5,3,1,4]}
  df = pd.DataFrame(data=d)

标签: python-3.xpandassortingdataframe

解决方案


由所有列用于DataFrame.sort_values测试是否相等并创建新列,例如DataFrame.assign

df1 = df.sort_values(['t1','t2','t3'], ascending=False).assign(new=range(1, len(df) + 1))
print (df1)
   id  t1  t2  t3  calculated  new
5  x6  16  11  16           1    1
1  x2  11  14   2           2    2
4  x5  10  22  16           3    3
6  x7   8   4  11           4    4
3  x4   4  15  18           5    5
2  x3   4   4  12           6    6
0  x1   3  20  14           7    7

如有必要,最后添加原始索引DataFrame.sort_index

df1 = df1.sort_index()
print (df1)
   id  t1  t2  t3  calculated  new
0  x1   3  20  14           7    7
1  x2  11  14   2           2    2
2  x3   4   4  12           6    6
3  x4   4  15  18           5    5
4  x5  10  22  16           3    3
5  x6  16  11  16           1    1
6  x7   8   4  11           4    4

推荐阅读