pythonif-statementpandas-loc

using an .loc and If statment


enter image description here

Use the .loc method, select the column rating for the rows of df where company_location equals "U.K."

Store it in a variable called uk_ratings.

uk_ratings = choco_df.loc[:, "rating"] 
if company_location == "U.K." :
print(uk_ratings)

I am used to using SQL not Python, so a little stuck, need help in where I am going one as this doesnt runn


Solution

  • In pandas conditions are expressed as masks (True or False) over each entry. So, in your case, to select the rating for UK companies you should:

    # 1. Consider only the rows corresponding to UK companies
    uk_company_mask = choco_df['company_location'] == 'U.K.'
    
    # 2. Take the rating column as a whole
    ratings = choco_df.loc[:, 'rating']
    
    # 3. Mask to consider only UK companies
    uk_ratings = ratings[uk_company_mask]
    

    Indeed, this can be done quite succinctly as follows:

    uk_ratings = choco_df.loc[choco_df['company_location'] == 'U.K.', 'rating']