Python - Pandas:在对角线上查找值

时间:2015-01-05 11:49:34

标签: python pandas

这有点复杂。我有多个数据框df,所有数据框都具有相同的列和索引,如下所示:

       E          F          H            
row                                                                     
CE     17.917153 10.875160   9.970251 
CF     9.780500  16.261098  10.021619    
CH     12.293967 10.608844  10.870527 

我在每个df中的目标是在数据框中找到两个最大值及其对应的indexcolumn。这些最大值不能在对角线上。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

from pandas import *


L = [[17.917153, 10.875160,   9.970251],   
     [9.780500,  16.261098,  10.021619], 
     [12.293967, 10.608844,  10.870527]]

df = DataFrame(L)

df2 = df.unstack().copy()

df2.sort()

IDX = df2[:].index

IDX = list(reversed(IDX))


M = []

for x in IDX[1:]:
    if(x[0]==x[1]):
        continue
    M.append(x);
    if(len(M)==2):
        break;

Max1 = M[0]
Max2 = M[1]


print "Max1 : ", Max1, "->", df2[Max1] 
print "Max2 : ", Max2, "->", df2[Max2]

输出:

Max1 :  (0, 2) -> 12.293967
Max2 :  (1, 0) -> 10.87516
         ^
       column