Python Calculate Average of Numbers Giving More Weights to Latest Numbers

Feb 21, 2021

Calculate Average

import numpy as npitems = [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.6items = [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]

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.