熊猫:按列的平均值对列进行排序

时间:2013-07-17 23:44:16

标签: python pandas

我在Pandas中有一个数据框,我想根据其列的平均值(或例如通过它们的std值)对其列进行排序(即获取新的数据帧或视图)。该文档讨论了sorting by label or value,但我在自定义排序方法上找不到任何内容。

我该怎么做?

2 个答案:

答案 0 :(得分:30)

您可以使用mean DataFrame方法和系列sort_values方法:

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

然后,您可以使用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

答案 1 :(得分:3)

您可以使用assign创建一个变量,使用它对值进行排序并将其放入同一行代码中。

df = pd.DataFrame(np.random.randn(4,4), columns=list('ABCD'))
df.assign(m=df.mean(axis=1)).sort_values('m').drop('m', axis=1)
相关问题