Get column names for max values over a certain row in a pandas DataFrame
<p>In the DataFrame</p>

<pre><code>import pandas as pd 
df=pd.DataFrame({'col1':[1,2,3],'col2':[3,2,1],'col3':[1,1,1]},index= ['row1','row2','row3'])
print df
       col1  col2  col3
row1     1     3     1
row2     2     2     1
row3     3     1     1
</code></pre>

<p>I want to get the column names of the cells with the max value(s) over a certain row. </p>

<p>The desired output would be (in pseudocode):</p>

<pre><code>get_column_name_for_max_values_of(row2)
&gt;['col1','col2']
</code></pre>

<p>What would be the most concise way to express   </p>

<pre><code>get_column_name_for_max_values_of(row2)
</code></pre>

<p>?</p>

<p>If not duplicates, you can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.idxmax.html" rel="nofollow"><code>idxmax</code></a>, but it return only first column of <code>max</code> value:</p>

<pre><code>print (df.idxmax(1))
row1    col2
row2    col1
row3    col1
dtype: object

def get_column_name_for_max_values_of(row):
    return df.idxmax(1).ix[row]

print (get_column_name_for_max_values_of('row2'))
col1
</code></pre>

<p>But with duplicates use <a href="http://pandas.pydata.org/pandas-docs/stable/indexing.html#boolean-indexing" rel="nofollow"><code>boolean indexing</code></a>:</p>

<pre><code>print (df.ix['row2'] == df.ix['row2'].max())
col1     True
col2     True
col3    False
Name: row2, dtype: bool

print (df.ix[:,df.ix['row2'] == df.ix['row2'].max()])
      col1  col2
row1     1     3
row2     2     2
row3     3     1

print (df.ix[:,df.ix['row2'] == df.ix['row2'].max()].columns)
Index(['col1', 'col2'], dtype='object')
</code></pre>

<p>And function is:</p>

<pre><code>def get_column_name_for_max_values_of(row):
    return df.ix[:,df.ix[row] == df.ix[row].max()].columns.tolist()

print (get_column_name_for_max_values_of('row2'))
['col1', 'col2']
</code></pre>

python pandas