简体   繁体   中英

Pandas how to select columns where a row has maximum value?

Let's say I have following dataframe:

df = pd.DataFrame({'A':[0.1,0.1,0.2],
                  'B': [0.22,0.2,0.22],
                  'C': [0.3, 0.2,0.333]})

df.index = list('abc')
df
     A     B      C
a  0.1  0.22  0.300
b  0.1  0.20  0.200
c  0.2  0.22  0.333

How to select all the columns where index b has maximum value.

Here, index has maximum value 2 in columns B, and C. So, the required answer is:

required_answer = ['B','C']

My attempts:

df[df.loc['b'] ==df.loc['b'].max()]

You can try this:

df.columns[df.loc['b'] == df.loc['b'].max()].tolist()
# ['B', 'C']

I give you several options. The first is the best:

[*df.columns[df.loc['b'].eq(df.loc['b'].max())]]

['B', 'C']

df.loc[:,df.loc['b'].eq(df.loc['b'].max())].columns.tolist()

['B', 'C']

[*df.T.index[df.loc['b'].eq(df.loc['b'].max())]]

['B', 'C']

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