如何按列值对数据框进行排序? [英] How to sort data frame by column values?

查看:62
本文介绍了如何按列值对数据框进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 和 pandas 数据框比较陌生,所以也许我在这里错过了一些很容易的东西.所以我有很多行和列的数据框,但最后终于设法从每列中获得最大值的一行.我用这个代码来做到这一点:

I am relatively new to python and pandas data frames so maybe I have missed something very easy here. So I was having data frame with many rows and columns but at the end finally manage to get only one row with maximum value from each column. I used this code to do that:

import pandas as pd

d = {'A' : [1.2, 2, 4, 6],
     'B' : [2, 8, 10, 12],
     'C' : [5, 3, 4, 5],
     'D' : [3.5, 9, 1, 11],
     'E' : [5, 8, 7.5, 3],
     'F' : [8.8, 4, 3, 2]}


df = pd.DataFrame(d, index=['a', 'b', 'c', 'd'])
print df

Out:
     A   B  C     D    E    F
a  1.2   2  5   3.5  5.0  8.8
b  2.0   8  3   9.0  8.0  4.0
c  4.0  10  4   1.0  7.5  3.0
d  6.0  12  5  11.0  3.0  2.0

然后从我使用这个函数的每一列中选择最大值:

Then to choose max value from each column I used this function:

def sorted(s, num):
    tmp = s.order(ascending=False)[:num]
    tmp.index = range(num)
    return tmp

NewDF=df.apply(lambda x: sorted(x, 1))
print NewDF

Out:
     A   B  C     D    E    F
0  6.0  12  5  11.0  8.0  8.8

是的,我丢失了行标签(无论索引),但保留此列标签对我来说更重要.现在我只需要根据其中的值对我需要前 5 列的列进行排序,我需要这个输出:

Yes, I lost row labels (indexes whatever) but this column labels are more important for me to retain. Now I just need to sort columns I need top 5 columns based on values inside them, I need this output:

Out:
   B     D   F    E    A    
0  12.0  11  8.8  8.0  6.0

我一直在寻找解决方案,但没有运气.我发现按列排序的最佳方法是 print NewDF.sort(axis=1) 但什么也没发生.

I was looking for a solution but with no luck. The best I found for sorting by columns is print NewDF.sort(axis=1) but nothing happens.

好的,我找到了一种方法,但要进行转换:

Ok, I found one way but with transformation:

transposed = NewDF.T
print(transposed.sort([0], ascending=False))

这是唯一可行的方法吗?

Is this the only possible way to do it?

推荐答案

您可以使用 maxnlargest,因为nlargest 对输出进行排序:

You can use max with nlargest, because nlargest sorts output:

print df.max().nlargest(5)
B    12.0
D    11.0
F     8.8
E     8.0
A     6.0
dtype: float64

然后转换为DataFrame:

print pd.DataFrame(df.max().nlargest(5)).T
      B     D    F    E    A
0  12.0  11.0  8.8  8.0  6.0

如果你需要对一行进行排序 DataFrame:

If you need sort one row DataFrame:

print NewDF.T.sort_values(0, ascending=False)
      0
B  12.0
D  11.0
F   8.8
E   8.0
A   6.0
C   5.0

另一个解决方案是applysort_values:

Another solution is apply sort_values:

print NewDF.apply(lambda x: x.sort_values(ascending=False), axis=1)
      B     D    F    E    A    C
0  12.0  11.0  8.8  8.0  6.0  5.0

这篇关于如何按列值对数据框进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆