Home > Software engineering >  Get the index of n maximum values in a column in dataframe
Get the index of n maximum values in a column in dataframe

Time:05-10

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.

CodePudding user response:

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

CodePudding user response:

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
  • Related