Python Calculate Average of Numbers Giving More Weights to Latest Numbers

February 21, 2021

Calculate Average

import numpy as np

items = [1, 2, 3, 4, 5]
value = np.average(items) # 3

Average where latest numbers have more weights

items = [1, 2, 3, 4, 5]
size = len(items)
weights = [pow(i+1, 1) for i in range(size)]  # [1, 2, 3, 4, 5]

value = np.average(items, weights=weights)    # 3.6

items = [5, 4, 3, 2, 1]
value = np.average(items, weights=weights)    # 2.33

You could adjust the weights

weights = [pow(i+1, 2) for i in range(size)] # [1, 4, 9, 16, 25]
weights = [pow(i+1, 0.5) for i in range(size)] # [1.0, 1.4142135623730951, 1.7320508075688772, 2.0, 2.23606797749979]
This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.