Pandas:按平均值对列进行排序 [英] Pandas: Sorting columns by their mean value
问题描述
我在 Pandas 中有一个数据框,我想根据其列的平均值(或例如通过它们的 std 值)对其列进行排序(即获取新的数据框或视图).该文档讨论了 按标签或值排序,但我找不到关于自定义排序方法的任何内容.
I have a dataframe in Pandas, I would like to sort its columns (i.e. get a new dataframe, or a view) according to the mean value of its columns (or e.g. by their std value). The documentation talks about sorting by label or value, but I could not find anything on custom sorting methods.
我该怎么做?
推荐答案
您可以使用 mean
DataFrame 方法和系列 sort_values
方法:
You can use the mean
DataFrame method and the Series sort_values
method:
In [11]: df = pd.DataFrame(np.random.randn(4,4), columns=list('ABCD'))
In [12]: df
Out[12]:
A B C D
0 0.933069 1.432486 0.288637 -1.867853
1 -0.455952 -0.725268 0.339908 1.318175
2 -0.894331 0.573868 1.116137 0.508845
3 0.661572 0.819360 -0.527327 -0.925478
In [13]: df.mean()
Out[13]:
A 0.061089
B 0.525112
C 0.304339
D -0.241578
dtype: float64
In [14]: df.mean().sort_values()
Out[14]:
D -0.241578
A 0.061089
C 0.304339
B 0.525112
dtype: float64
然后您可以使用 对列重新排序重新索引
:
Then you can reorder the columns using reindex
:
In [15]: df.reindex(df.mean().sort_values().index, axis=1)
Out[15]:
D A C B
0 -1.867853 0.933069 0.288637 1.432486
1 1.318175 -0.455952 0.339908 -0.725268
2 0.508845 -0.894331 1.116137 0.573868
3 -0.925478 0.661572 -0.527327 0.819360
<小时>
注意:在早期版本的 Pandas 中,sort_values
曾经是 order
,但 order
作为 0.17 的一部分被弃用,因此与其他排序方法更加一致.此外,在早期版本中,必须使用 reindex_axis
而不是 reindex
.
Note: In earlier versions of pandas, sort_values
used to be order
, but order
was deprecated as part of 0.17 so to be more consistent with the other sorting methods. Also, in earlier versions, one had to use reindex_axis
rather than reindex
.
这篇关于Pandas:按平均值对列进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!