简体   繁体   中英

Python - Pandas: Find largests values off-diagonal

This is somewhat complicated. I have multiple dataframes df , all with the same columns and index that looks like the one below:

       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 

My objective in each df is to find the two maximum values in the dataframe and their corresponding index and column . These max values cannot be on the diagonal . How can I do so?

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]

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM