get row and column names of n maximum values in dataframe
<p>For the dataframe </p>

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

<p>I want to get the row name and the col name of the 2 maximum values and the according maximum values, such that the resulting expression returns something like this: </p>

<pre><code>[(row1,col2,4)(row2,col2,5)]
</code></pre>

<p>Whats the most concise way to do that in pandas?</p>

<p>You can use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> for creating <code>Series</code>, then <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.nlargest.html" rel="nofollow"><code>Series.nlargest</code></a> with <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.reset_index.html" rel="nofollow"><code>reset_index</code></a> and last create <code>tuples</code> by list comprehension:</p>

<pre><code>print (df)
      col1  col2
row1     1     4
row2     2     5

df1 = df.stack().nlargest(2).reset_index()
print (df1)
  level_0 level_1  0
0    row2    col2  5
1    row1    col2  4

tuples = [tuple(x) for x in df1.values]
print (tuples)
[('row2', 'col2', 5), ('row1', 'col2', 4)]
</code></pre>

python pandas