根据列对DataFrame进行Argsort排序

5
我有以下DataFrame:
userId column_1 column_2 column_3
A 4.959 3.231 1.2356
B 0.632 0.963 2.4556
C 3.234 7.445 5.3435
D 1.454 0.343 2.2343
我想要按照上一篇文章的列进行argsort:
userId first second third
A column_3 column_2 column_1
B column_1 column_2 column_3
C column_1 column_3 column_2
D column_2 column_1 column_3

似乎他正在对行进行排序,而不是打印列名的数字。 - adir abargil
基本上,我想为每个用户订购值。对于用户A,最低值的列是'column_3',第二列是'column_2',最高值的列是'column_1'。 - Javier Monsalve
@Craig 但是你如何在其中插入列名? - adir abargil
非常感谢您提供的精彩答案!让我也变得更聪明了... - adir abargil
2个回答

9

您可以在轴1上使用np.argsort。然后使用pd.Index.to_numpydf.columns转换为numpy数组,再使用numpy indexing

df = df.set_index('userId') # If userId is not index already.
idx = df.values.argsort(axis=1)
out = pd.DataFrame(df.columns.to_numpy()[idx], index=df.index)

               0         1         2
userId
A       column_3  column_2  column_1
B       column_1  column_2  column_3
C       column_1  column_3  column_2
D       column_2  column_1  column_3

2
设置索引后,df.columns.to_numpy()[np.argsort(df)] 也应该可以工作 :-) - anky

2
另一种方法是使用 stack() 结合 sort_values()map 来设置自定义列标题。
mapper_ = {1 : 'first', 2 : 'second', 3 : 'third', 4 : 'fourth'}
s = (df.set_index('userId').stack().sort_values().groupby(level=0).cumcount() + 1).map(mapper_)

s.reset_index(1).set_index(0,append=True).unstack(0)




        level_1                    
0          first    second     third
userId                              
A       column_3  column_2  column_1
B       column_1  column_2  column_3
C       column_1  column_3  column_2
D       column_2  column_1  column_3

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接