将按行排序的数据框映射到原始列标签( pandas ) [英] Mapping row-wise sorted dataframe to original column labels (Pandas)
问题描述
我正面临涉及数据框架的问题,因此在Google花费了大量时间后,我在这里提出了一个问题. 我有一个数据框-
I am facing this problem involving dataframes, so after spending a lot of time on Google, I am opening a question here. I am having a Dataframe -
df
A B C D
0 8 3 6 2
1 1 -3 5 2
2 4 9 5 10
3 2 -4 -8 -2
我想按降序对每一行进行排序,但我不想保存值,而是要保存对应的列名.
I want to sort every row in descending order, but instead of saving the values, I want to save the corresponding column name.
排序的数据框看起来像这样-
Sorted dataframe would look like this -
df
A B C D
0 8 6 3 2
1 5 2 1 -3
2 10 9 5 4
3 2 -2 -4 -8
我最终想要的是下面的结构,它对应于排序后的数据框df
-
What I ultimately want is this structure below, which corresponds to the column indices of the sorted dataframe df
-
df_col
1 2 3 4
0 A C B D
1 C D A B
2 D B C A
3 A D B C
我敢肯定,如果没有明确的for loop
I am sure there will be a simpler one liner solution to this problem, without coding an explicit for loop
推荐答案
应用np.argsort
,对索引进行排序,然后索引到df.columns
.
Apply np.argsort
, sort the indices, and then index into df.columns
.
In [129]: pd.DataFrame(df.columns[df.apply(np.argsort, axis=1).T[::-1].T])
Out[129]:
0 1 2 3
0 A C B D
1 C D A B
2 D B C A
3 A D B C
这篇关于将按行排序的数据框映射到原始列标签( pandas )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!