Max function in python for country data

Viewed 25

Hi I have an example dataset of the following: enter image description here

I am trying to use the max function to find the top 3 countries with the highest number of hotels.

I used the following code in python: print(data['Number of hotels'].max)

However, it doesn't give the exact name of the country when printing this code. Any suggestions would be appreciated

3 Answers

If you're importing your list of hotels and numbers from a CSV then you are likely dealing with a list of lists. Something like this would work:

number_of_hotels = [
    ['Canada', 6555], 
    ['USA', 66666], 
    ['UK', 77777],
    ['Australia', 1000000]
]

print(max(number_of_hotels, key=lambda x: x[1]))
['Australia', 1000000]

No need for extra library imports.

You can use Counter from collections

from collections import Counter

country_hotels = {
    'Canada': 6555, 
    'USA': 66666, 
    'UK': 77777,
    'Australia': 1000000
}

print(Counter(country_hotels).most_common(1)[0]) #('Australia', 1000000)

Since you seem to be dealing with a pd.DataFrame, you can achieve this with df.nlargest. (Check the keep parameter on how to handle potential duplicates.)

Setup

data = pd.DataFrame({'Countries': [*'ABCDE'],
        'Number of hotels': np.random.randint(0,100,5)})

print(data)

  Countries  Number of hotels
0         A                22
1         B                99
2         C                83
3         D                 7
4         E                72

Code

data.nlargest(n=3, columns='Number of hotels')

  Countries  Number of hotels
1         B                99
2         C                83
4         E                72

Also possible with df.sort_values. I.e.:

data.sort_values(by=['Number of hotels'], ascending=False).iloc[:3]
Related