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:
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()]