Currently have a dataframe that is countries by series, with values ranging from 0-25
I want to sort the df so that the highest values appear in the top left (first), while the lowest appear in the bottom right (last).
来自
A B C D ...
USA 4 0 10 16
CHN 2 3 13 22
UK 2 1 8 14
...
至
D C A B ...
CHN 22 13 2 3
USA 16 10 4 0
UK 14 8 2 1
...
在此,具有最高值的列现在位于第一个,索引也是如此。
I have considered reindexing, but this loses the 'Countries' Index.
D C A B ...
0 22 13 2 3
1 16 10 4 0
2 14 8 2 1
...
I have thought about creating a new column and row that has the Mean or Sum of values for that respective column/row, but is this the most efficient way?
block 引用> block 引用>How would I then sort the DF after I have the new rows/columns??
有没有办法使用...重新索引
df_mv.reindex(df_mv.mean(or sum)().sort_values(ascending = False).index, axis=1)
...这将允许我保留国家索引,并简单地进行相应的排序?
感谢您的任何建议或帮助。
EDIT
Intended result organizes columns AND rows from largest to smallest.
block 引用> block 引用>Regarding the first row of the A and B columns in the intended output, these are supposed to be 2, 3 respectively. This is because the intended result interprets the A column as greater than the B column in both sum and mean (even though either sum or mean can be considered for the 'value' of a row/column).
通过说较高的数字位于左上角,而较低的数字位于右下角,我只是表示这是结果 df 的总体趋势。然而,列和行作为一个整体才是预期的焦点。对于造成的困惑,我深表歉意。
最佳答案
您可以使用:
rows_index=df.max(axis=1).sort_values(ascending=False).index
col_index=df.max().sort_values(ascending=False).index
new_df=df.loc[rows_index,col_index]
print(new_df)
D C A B
CHN 22 13 2 3
USA 16 10 4 0
UK 14 8 2 1
关于python - 同时按行和列降序对 Dataframe 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59147397/