Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get the columns name of the two largest values from pandas dataframe rows

I have the following pandas data frame:

    AA    BB    CC    DD    EE
----------------------------------
0   1     12    4      3     5
1   5     7     28     7     4
2   9     7     9      2     6

I would like to add a new column ("MM") and set it to be a list of the column names of the two largest values in each row, for the above data frame, the output should be:

    AA    BB    CC    DD    EE    MM
-------------------------------------------------
0   1     12    4      3     5    ['BB','EE']
1   5     7     28     7     4    ['CC','DD','BB']
2   9     7     9      2     6    ['AA','CC']

in the first row, the two largest values are: 12,5 (column ‘BB’ and ‘EE’)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I do that ?

Thanks

>Solution :

You can use apply with nlargest and the keep='all' parameter to keep the duplicates:

df['MM'] = df.apply(lambda r: r.nlargest(2, keep='all').index.values, axis=1)

output:

   AA  BB  CC  DD  EE            MM
0   1  12   4   3   5      [BB, EE]
1   5   7  28   7   4  [CC, BB, DD]
2   9   7   9   2   6      [AA, CC]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading