Exploring Data With Pandas — Using Loops With Pandas | Dataquest


Fri Sep 16 2022 10:40:35 GMT+0000 (UTC)

Saved by @ggriffin60 #python

top_employer_by_country = {}

countries = f500['country'].unique()

for c in countries:
    # select only the rows that have a country name equal to current iteration
    selected_rows = f500[f500['country'] == c]
    # sort the rows by employees column in descending order
    sorted_rows = selected_rows.sort_values('employees', ascending=False)
    # select the first row from the sorted dataframe
    top_employer = sorted_rows.iloc[0]
    # extract the company name from the index label company from the first row
    employer_name = top_employer['company']
    # assign the results to dictionary using country name as the key and company name as the        value
    top_employer_by_country[c] = employer_name