The Wayback Machine - https://web.archive.org/web/20240802004838/https://www.geeksforgeeks.org/how-to-calculate-weighted-average-in-pandas/
Open In App

How to Calculate Weighted Average in Pandas?

Last Updated : 09 Dec, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

A weighted average is a computation that considers the relative value of the integers in a data collection. Each value in the data set is scaled by a predefined weight before the final computation is completed when computing a weighted average.

Syntax:

def weighted_average(dataframe, value, weight):
    val = dataframe[value]
    wt = dataframe[weight]
    return (val * wt).sum() / wt.sum()

It will return the weighted average of the item in value. In the numerator, we multiply each value with the corresponding weight associated and add them all. In the denominator, all the weights are added. 

Approach

  • We take a data frame or make our own data frame.
  • Define a function to calculate the weighted average by the above-mentioned formula.
  • We need to have at least three items in the data frame i.e index (which may be item-name, date, or any such variable), value, and weight.
  • We will make a function call passing all these three values.

Example:

Let us see an example to calculate the weighted average of value grouped by item_name. 

Suppose there are three shops and each shop contains three items i.e Chocolates, IceCream and Biscuits. We have the weight of each of the items and the price of each of the items in all the three shops. Now we need to find out the weighted average of each item. 

Python3




import pandas as pd
 
 
def weighted_average(dataframe, value, weight):
    val = dataframe[value]
    wt = dataframe[weight]
    return (val * wt).sum() / wt.sum()
 
 
# creating a dataframe to represent different
# items and their corresponding weight and value
dataframe = pd.DataFrame({'item_name': ['Chocolate', 'Chocolate',
                                        'Chocolate', 'Biscuit',
                                        'Biscuit', 'Biscuit',
                                        'IceCream', 'IceCream',
                                        'IceCream'],
                          'value': [90, 50, 86, 87, 42, 48,
                                    68, 92, 102],
                          'weight': [4, 2, 3, 5, 6, 5, 3, 7,
                                     5]})
 
# Weighted average of value  grouped by item name
dataframe.groupby('item_name').apply(weighted_average,
                                     'value', 'weight')


Output:

Using groupby()

Here we are going to group the items using groupby() function and calculate the weights by grouping these items along with sum function. So By using this method we are just forming a group of  similar items to get the sum

Syntax :

def weighted_average_of_group(values, weights, item):
    return (values * weights).groupby(item).sum() / weights.groupby(item).sum()

Example:

Python3




import pandas as pd
 
 
def weighted_average_of_group(values, weights, item):
    return (values * weights).groupby(item).sum() / weights.groupby(item).sum()
 
 
# creating a dataframe to represent different items
# and their corresponding weight and value
dataframe = pd.DataFrame({'item_name': ['Chocolate', 'Chocolate', 'Chocolate',
                                        'Biscuit', 'Biscuit', 'Biscuit',
                                        'IceCream', 'IceCream', 'IceCream'],
                          'value': [90, 50, 86, 87, 42, 48, 68, 92, 102],
                          'weight': [4, 2, 3, 5, 6, 5, 3, 7, 5]})
 
# Finding grouped average of group
weighted_average_of_group(values=dataframe.value,
                          weights=dataframe.weight, item=dataframe.item_name)


Output:

To calculate the weighted average of the whole data frame (not of every group, but as a whole) we will use the syntax shown below:

Syntax

def weighted_average_of_whole_dataframe(dataframe, value, weight):
    val = dataframe[value]
    wt = dataframe[weight]
    return (val * wt).sum() / wt.sum()

Example:

Python3




import pandas as pd
 
 
def weighted_average(dataframe, value, weight):
    val = dataframe[value]
    wt = dataframe[weight]
    return (val * wt).sum() / wt.sum()
 
 
# creating a dataframe to represent different items
# and their corresponding weight and value
dataframe = pd.DataFrame({'item_name': ['Chocolate', 'Chocolate', 'Chocolate',
                                        'Biscuit', 'Biscuit', 'Biscuit',
                                        'IceCream', 'IceCream', 'IceCream'],
                          'value': [90, 50, 86, 87, 42, 48, 68, 92, 102],
                          'weight': [4, 2, 3, 5, 6, 5, 3, 7, 5]})
 
# Weighted average of whole dataframe as a whole
weighted_average(dataframe, 'value', 'weight')


Output:

75.075


Similar Reads

Compute the weighted average of a given NumPy array
In NumPy, we can compute the weighted of a given array by two approaches first approaches is with the help of numpy.average() function in which we pass the weight array in the parameter. And the second approach is by the mathematical computation first we divide the weight array sum from weight array then multiply with the given array to compute the
2 min read
How to calculate MOVING AVERAGE in a Pandas DataFrame?
In this article, we will be looking at how to calculate the moving average in a Pandas data frame. Moving Average calculates the average of data over some periods. The moving average is also known as the rolling mean and is calculated by averaging data of the time series within k periods.  Calculating Moving Averages using PandasThere are various m
8 min read
Calculate average values of two given NumPy arrays
Finding average of NumPy arrays is quite similar to finding average of given numbers. We just have to get the sum of corresponding array elements and then divide that sum with the total number of arrays. Let's see an example: Example 1: Calculate average values of two given NumPy 1d-arrays C/C++ Code # import library import numpy as np # create a n
1 min read
How to Calculate an Exponential Moving Average in Python?
Moving Averages are financial indicators which are used to analyze stock values over a long period of time. i.e. Average value for that long period is calculated. Exponential Moving Averages (EMA) is a type of Moving Averages. It helps users to filter noise and produce a smooth curve. In Moving Averages 2 are very popular. Simple Moving AverageExpo
3 min read
Calculate Average Street Circuity Using OSMnx stats Module
Circuity is defined as a lack of straightforwardness and it is a result of a circulation network configuration. It impacts how we use urban space for settlement and travel. Calculating the average circuity of a city provides insights about direct routes in a transportation network. In this article, we will see how to calculate average street circui
2 min read
How to get weighted random choice in Python?
Weighted random choices mean selecting random elements from a list or an array by the probability of that element. We can assign a probability to each element and according to that element(s) will be selected. By this, we can select one or more than one element from the list, And it can be achieved in two ways. By random.choices()By numpy.random.ch
3 min read
How To Implement Weighted Mean Square Error in Python?
In this article, we discussed the implementation of weighted mean square error using python. Mean squared error is a vital statistical concept, that is nowadays widely used in Machine learning and Deep learning algorithm. Mean squared error is basically a measure of the average squared difference between the estimated values and the actual value. I
2 min read
Use Pandas to Calculate Statistics in Python
Performing various complex statistical operations in python can be easily reduced to single line commands using pandas. We will discuss some of the most useful and common statistical operations in this post. We will be using the Titanic survival dataset to demonstrate such operations. C/C++ Code # Import Pandas Library import pandas as pd # Load Ti
6 min read
Python | Pandas Series.mad() to calculate Mean Absolute Deviation of a Series
Pandas provide a method to make Calculation of MAD (Mean Absolute Deviation) very easy. MAD is defined as average distance between each value and mean. The formula used to calculate MAD is: Syntax: Series.mad(axis=None, skipna=None, level=None) Parameters: axis: 0 or ‘index’ for row wise operation and 1 or ‘columns’ for column wise operation. skipn
2 min read
Calculate the number of characters in each word in a Pandas series
To calculate the numbers of characters we use Series.str.len(). This function returns the count of the characters in each word in a series. Syntax: Series.str.len() Return type: Series of integer values. NULL values might be present too depending upon caller series. Another way to find the number of characters by using len() function (that wrapped
2 min read
Practice Tags :
three90RightbarBannerImg