简体   繁体   English

特殊排序列数据框

[英]Special Sorting columns dataframes

I have the dataframre below.我有下面的数据框。

 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)

I want to do add column that contains the sort on t1 then if for two lines we have t1 equal then we can have a look on t2 and do the same thing.我想在 t1 上添加包含排序的列,然后如果两行的 t1 相等,那么我们可以查看 t2 并做同样的事情。 My column will contain.我的专栏将包含。

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

My dataframe expected will be:我的 dataframe 预计将是:

 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)

Use DataFrame.sort_values by all columns for test if equal and create new column eg by DataFrame.assign :通过所有列使用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

Last if necessary original index add DataFrame.sort_index :最后如果需要原始索引添加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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM