Weighted mean function

Screen Link: https://app.dataquest.io/m/306/the-weighted-mean-and-the-median/3/the-weighted-mean

I didnt really follow the code for the DQ answer since they used the zip() function, so I thought I would share my answer.

My Code:

def weighted_mean(means, weights):
    total_values = (means * weights) #create a new array with a vectorized operation
    sum_values = total_values.sum() #aggregate the new array
    weight = weights.sum() #aggregate the weight array
    mean = sum_values / weight #calculate the mean using the aggregations
    return mean
    
weighted_mean_function = weighted_mean(houses_per_year['Mean Price'], houses_per_year['Houses Sold'])

from numpy import average

weighted_mean_numpy = average(houses_per_year['Mean Price'], weights=houses_per_year['Houses Sold'])        

equal = round(weighted_mean_function, 10) == round(weighted_mean_numpy, 10)

Hope this helps somebody.

1 Like

Hey ncarvey. Thanks for posting this, and it does help me. I saw DQ answer with the zip function, but I’ve never used it before.

2 Likes