python - 同时按行和列降序对 Dataframe 进行排序

标签 python pandas sorting dataframe indexing

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?

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.

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/

相关文章:

python - Pandas 拆分列值并分配回该列

java - 如何按数字对包含另一张 map 的 map 进行排序

python - coinbase-api python 库入门

python - 不同数量的 map task (1、2、4 ..)之间没有性能差异

python - pandas python 中的日期范围问题

python - 使用 python pandas .to_csv 附加到 csv 时如何强制换行

javascript - javascript中的自定义排序功能不起作用

javascript - 如何在javascript中按变量值的int部分对数组进行排序?

python - Pyinstaller 创建空 Dist 文件夹

python - 蓝图和工厂模式一起工作?