简体   繁体   中英

Sort pandas dataframe by index

I have the following pandas dataframe:

    Cmpd1   Cmpd2   Cmpd3   Cmpd4   Cmpd5   Cmpd6
Cmpd1   1                   
Cmpd2   0.4   1             
Cmpd3   0.6   0.3   1           
Cmpd4   0.46  0.69  0.32    1       
Cmpd5   0.57  0.44  0.41    0.51    1   
Cmpd6   0.41  0.79  0.33    0.56    0.43    1

I would like to order it from highest to lowest based on the index no matter if it is repeated, what I say would look like this:

The maximum value corresponds to Cmpd6 = 0.79, followed by Cmpd4 = 0.69 ... at some point Cmpd6 = 0.56 which I would like to leave the list like this:

Cmpd6 = 0.79
Cmpd4 = 0.69
Cmpdx = x
Cmpd6 = 0.56

This with each value of the array, no matter how many times the indexes are repeated, I was trying with .sort_index (axis = 1) but it does not produce any of this, I also tried .ravel () but it does not give me the indexes. How can i fix this?

Thanks!

My solution:

df = df.where(np.tril(np.ones(df.shape), -1).astype(np.bool))
df = df.stack().reset_index().drop("level_1", axis=1).sort_values(by=0, ascending=False)

I assume that each empty element in the source df contain actualy an empty string (not NaN , as these would be printed just as NaN ).

I also noticed that you want to keey only values < 1 .

To get your result, run:

s = df.stack()
s[s.apply(lambda x: type(x) is not str and x < 1)]\
    .reset_index(level=1, drop=True).sort_values(ascending=False)\
    .astype(float)

For your data the result is:

Cmpd6    0.79
Cmpd4    0.69
Cmpd3    0.60
Cmpd5    0.57
Cmpd6    0.56
Cmpd5    0.51
Cmpd4    0.46
Cmpd5    0.44
Cmpd6    0.43
Cmpd6    0.41
Cmpd5    0.41
Cmpd2    0.40
Cmpd6    0.33
Cmpd4    0.32
Cmpd3    0.30
dtype: float64

Other possible solution:

s = df.replace(r'^\s*$', np.nan, regex=True).stack()\
    .reset_index(level=1, drop=True).sort_values(ascending=False)
s[s < 1]

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