TKTK
TKTK

Reputation: 57

how to iterate over entries in list while defining own function

I'm trying to defining a function with these goals.

The function should return the average value for the given metric for the given list of countries. in layman's terms. I want the function to pull every back every country's given value repsective to what column is mentioned. then sum all entries in the list and divide by len if this is a list

g7 = ['United States', 'Italy', 'Canada', 'Japan', 'United Kingdom', 'Germany', 'France']

This is my code so far:

def countries_average(df,cl,column):
    average = []
    for country in enumerate(cl):
        x = df.loc[df["location"] == country, column]
        average.append(x)
        y = sum(average)/len(average)
        return average

it returns, instead, a row from the first entry in the list. when one of the entries in column are total_deaths:

[28543    127410.0
 Name: total_deaths, dtype: float64]

any help iterating over this list and adding to average list successfully. I tried range(len(cl)) but that didn't help either. any help would be appreciated.

Upvotes: 0

Views: 64

Answers (1)

DDD1
DDD1

Reputation: 450

I think this should work:

def countries_average(df,cl,column):
    return df[df['location'].isin(cl)][column].mean()

Upvotes: 2

Related Questions