pandas 熊猫:按最大值对列进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40111161/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pandas: Sort column by maximum values
提问by RPacker
Suppose we have following dataframe:
假设我们有以下数据框:
A B C D
1 5 16 1
5 30 45 10
2 40 60 5
4 15 40 7
Here, we need to sort the columns according to their maximum values. Accordingly, the columns should be sorted like:
在这里,我们需要根据它们的最大值对列进行排序。因此,列应按如下方式排序:
C B D A
because max(C)=60, max(B)=40, max(D)=10, max(A)=5.
因为 max(C)=60, max(B)=40, max(D)=10, max(A)=5。
What's the best way to automate this?
自动化此过程的最佳方法是什么?
回答by EdChum
You can sort the result from df.max
and use this to reindex the df:
您可以对结果进行排序df.max
并使用它来重新索引 df:
In [64]:
df.ix[:, df.max().sort_values(ascending=False).index]
Out[64]:
C B D A
0 16 5 1 1
1 45 30 10 5
2 60 40 5 2
3 40 15 7 4
breaking the above down:
分解上述内容:
In [66]:
df.max()
Out[66]:
A 5
B 40
C 60
D 10
dtype: int64
In [67]:
df.max().sort_values(ascending=False)
Out[67]:
C 60
B 40
D 10
A 5
dtype: int64