简体   繁体   English

(Python/Pandas) 排序值时的数据透视表

[英](Python/Pandas) Pivot table while sorting values

user_id_2     1        2          3         4         5    
user_id_1                                                                      
   1      0.000000  0.707107  0.388075  0.668153  0.559017  
   2      0.707107  0.000000  0.504916  0.491354  0.632456  
>> 3      0.388075  0.504916  0.000000  0.373383  0.225618 <<
   4      0.668153  0.491354  0.373383  0.000000  0.448211  
   5      0.559017  0.632456  0.225618  0.448211  0.000000  

These are the results of some computations.这是一些计算的结果。 I was wondering if I could choose a row and rank the highest value with the columns.我想知道我是否可以选择一行并对列中的最高值进行排名。

Eg.例如。 Choosing row user_id_1(3)选择行user_id_1(3)

user_id_1      user_id_2
    3              2
    3              1
    3              4
    3              5
    3              3

Use Series.argsort in descending order of selected row by DataFrame.loc , get new order of columns names and create new DataFrame by constructor:DataFrame.loc所选行的降序使用Series.argsort ,获取列名的新顺序并通过构造函数创建新的 DataFrame :

val = 3
df = pd.DataFrame({'user_id_1':val, 
                   'user_id_2':df.columns[(-df.loc[val]).argsort()]})

print (df)
   user_id_1 user_id_2
0          3         2
1          3         1
2          3         4
3          3         5
4          3         3

Or if want only order add 1 :或者,如果只想订购添加1

val = 3
df = pd.DataFrame({'user_id_1':val, 
                   'user_id_2':(-df.loc[val]).argsort() + 1})

print (df)
   user_id_1  user_id_2
1          3          2
2          3          1
3          3          4
4          3          5
5          3          3

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

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