BhishanPoudel
BhishanPoudel

Reputation: 17164

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()]

Upvotes: 0

Views: 56

Answers (2)

ansev
ansev

Reputation: 30940

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']

Upvotes: 1

BhishanPoudel
BhishanPoudel

Reputation: 17164

You can try this:

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

Upvotes: 1

Related Questions