0

I want to return the name of the country with the maximum number of gold medals in the 'Gold' column.

# Summer    Gold    Silver  Bronze  Total   # Winter    Gold.1  Silver.1    Bronze.1    Total.1 # Games Gold.2  Silver.2    Bronze.2    Combined total  ID
Afghanistan 13  0   0   2   2   0   0   0   0   0   13  0   0   2   2   AFG
Algeria 12  5   2   8   15  3   0   0   0   0   15  5   2   8   15  ALG
Argentina   23  18  24  28  70  18  0   0   0   0   41  18  24  28  70  ARG
Armenia 5   1   2   9   12  6   0   0   0   0   11  1   2   9   12  ARM
Australasia 2   3   4   5   12  0   0   0   0   0   2   3   4   5   12  ANZ     

The following code returns the row object and I want to extract the name of the country which is the index of that row.

def return_max_name():

    return df.loc[df['Gold'].idxmax()]

return_max_name()

Here is what is returned:

# Summer            26
Gold               976
Silver             757
Bronze             666
Total             2399
# Winter            22
Gold.1              96
Silver.1           102
Bronze.1            84
Total.1            282
# Games             48
Gold.2            1072
Silver.2           859
Bronze.2           750
Combined total    2681
ID                 USA
Name: United States, dtype: object

I want the function to return 'United States'. I am new to Pandas and I am kinda stuck here so any kind of help will be great!

6
  • kindly share ur input data Commented Apr 20, 2020 at 20:54
  • Okay. I have added the input data Commented Apr 20, 2020 at 20:59
  • 2
    set the country column as index and run this code : df.Gold.idxmax(). it should give u Argentina based on ur shared data Commented Apr 20, 2020 at 21:04
  • Yeah that works, thanks a lot!! Commented Apr 20, 2020 at 21:06
  • 1
    then u have to use bracket indexing ... df['Gold.1'] Commented Apr 20, 2020 at 22:24

1 Answer 1

1

If you found the right row, and the # Summer column has the country name, you can get that name by adding the column param to loc.

Try changing your return line to this.

return df.loc[df.Gold.idxmax(), '# Summer']
Sign up to request clarification or add additional context in comments.

2 Comments

The country is already the index of the datagram. I didn't know how to post the dataframe here that's why the data has the indentation problem
sammywemmy's solution and this one should do the same thing. If the country was not the index, this would allow you to avoid changing the index.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.