'Get the index of n maximum values in a column in dataframe

I have a data frame and I want to get the index and value of the 4 maximum values in each rows. For example, in the following df, in column a, 10, 6, 7, 8 are four maximum values.

import pandas as pd
df = pd.DataFrame()
df['a'] = [10, 2, 3, -1,4,5,6,7,8]
df['id'] = [100, 2, 3, -1,4,5,0,1,2]
df

The output which I want is:

enter image description here

Thanks for your help.



Solution 1:[1]

Try nlargest,

df.nlargest(4, 'a').reset_index()

Output:

   index   a   id
0      0  10  100
1      8   8    2
2      7   7    1
3      6   6    0

Solution 2:[2]

You can sort the a column

out = (df.sort_values('a', ascending=False).iloc[:4]
       .sort_index(ascending=True)
       .reset_index())
print(out)

   index   a   id
0      0  10  100
1      6   6    0
2      7   7    1
3      8   8    2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2