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

return the name of the row(first column) of the maximum difference between two columns

I have a dataframe like this :

  Country   1990  1995 2000 2005 2010  2015
0   Bahrain     5     4    3    2   1    20
1   Maldives   10     9    8    7   6    30
2   Germany    7      4    3    2   1    40
.      ....     ..    ..   ..    ..  ..  ..
.      ....     ..    ..   ..    ..  ..  ..
.      ....     ..    ..   ..    ..  ..  ..

I want to calculate the difference between column 2015 and 1990 and then return the name of the row with the maximum difference.
In this case is Germany.

I wrote this:

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

highest_growth =(df['2020']-df['1990']).abs().idxmax()

which returns the index of the country with the maximum difference but I want to have the name of the country as a string output.
I don’t want an extra column.Just returning the name of the country with the max value of df[‘2020’]-df[‘1990’].

>Solution :

With the index of the row, you can get the country name by indexing df['Country']:

highest_growth_index = (df['2020']-df['1990']).abs().idxmax()
highest_growth = df['Country'][highest_growth_index]

In one line:

highest_growth = df['Country'][(df['2020']-df['1990']).abs().idxmax()]
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