Largest (n) numbers with Index and Column name in Pandas DataFrame
<p>I wish to find out the largest 5 numbers in a DataFrame and store the Index name and Column name for these 5 values.</p>

<p>I am trying to use    nlargest() and idxmax methods but failing to achieve what i want. My code is as below:</p>

<pre><code>import numpy as np
import pandas as pd
from pandas import Series, DataFrame
df = DataFrame({'a': [1, 10, 8, 11, -1],'b': [1.0, 2.0, 6, 3.0, 4.0],'c': [1.0, 2.0, 6, 3.0, 4.0]})
</code></pre>

<p>Can you kindly let me know How can i achieve this. Thank you</p>

<p>Use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.stack.html" rel="nofollow"><code>stack</code></a> and <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.nlargest.html" rel="nofollow"><code>nlargest</code></a>:</p>

<pre><code>max_vals = df.stack().nlargest(5)
</code></pre>

<p>This will give you a Series with a multiindex, where the first level is the original DataFrame's index, and the second level is the column name for the given value.  Here's what <code>max_vals</code> looks like:</p>

<pre><code>3  a    11.0
1  a    10.0
2  a     8.0
   b     6.0
   c     6.0
</code></pre>

<p>To explicitly get the index and column names, use <a href="http://pandas.pydata.org/pandas-docs/stable/generated/pandas.MultiIndex.get_level_values.html" rel="nofollow"><code>get_level_values</code></a> on the index of <code>max_vals</code>:</p>

<pre><code>max_idx = max_vals.index.get_level_values(0)
max_cols = max_vals.index.get_level_values(1)
</code></pre>

<p>The result of <code>max_idx</code>:</p>

<pre><code>Int64Index([3, 1, 2, 2, 2], dtype='int64')
</code></pre>

<p>The result of <code>max_cols</code>:</p>

<pre><code>Index(['a', 'a', 'a', 'b', 'c'], dtype='object')
</code></pre>

python pandas numpy dataframe data-analysis