The dot product inclination is correct, and that includes the sum you need. So, to get the sum of the products of the elements of a target array and a set of weights:

>>> a = np.array([[0,1,2],[2,2,3]])
>>> a
array([[0, 1, 2],
       [2, 2, 3]])
>>> weights = np.array([16,4,2])
>>> np.dot(a,weights)
array([ 8, 46])
Answer from Karmel on Stack Overflow
🌐
NumPy
numpy.org › doc › 2.1 › reference › generated › numpy.average.html
numpy.average — NumPy v2.1 Manual
The only constraint on the values of weights is that sum(weights) must not be 0.
🌐
GitHub
github.com › numpy › numpy › issues › 29863
ENH: Add weights-parameter to numpy.ndarray.sum · Issue #29863 · numpy/numpy
October 2, 2025 - An array of weights associated with the values in a. Each value in a contributes to the sum according to its associated weight. The array of weights must be the same shape as a if no axis is specified, otherwise the weights must have dimensions ...
Author: numpy
🌐
w3resource
w3resource.com › python-exercises › numpy › python-numpy-stat-exercise-6.php
NumPy: Compute the weighted of a given array - w3resource
The resulting value is assigned to r1. r2 = (x*(weights/weights.sum())).sum(): This code calculates the weighted average manually using the formula r2 = (x*(weights/weights.sum())).sum().
🌐
NumPy
numpy.org › doc › stable › reference › generated › numpy.average.html
numpy.average — NumPy v2.5 Manual
The only constraint on the values of weights is that sum(weights) must not be 0.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to calculate the weighted average of a numpy array in python?
How to Calculate the Weighted Average of a Numpy Array in Python? - Be on the Right Side of Change
January 9, 2023 - Definition weighted average: Each array element has an associated weight. The weighted average is the sum of all array elements, properly weighted, divided by the sum of all weights.
🌐
Newton
newton.cx › ~peter › howto › take-a-2d-weighted-average-in-numpy
PKGW: How-To: Take a 2D weighted average in Numpy
October 15, 2018 - We sum # along the 1-th axis, which is counted starting from zero -- so # we're summing along the rightmost axis, the one of size 10. r_weights = r_uncerts ** -2 wt_avg = (r_data * r_weights).sum(axis=1) / r_weights.sum(axis=1) uncert_wt_avg = 1 / np.sqrt(r_weights.sum(axis=1))
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › compute-the-weighted-average-of-a-given-numpy-array
Compute the weighted average of a given NumPy array | GeeksforGeeks
August 29, 2020 - 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 sum of that array.
🌐
Medium
medium.com › @whyamit101 › understanding-weighted-average-with-numpy-cfb245fced2a
Understanding Weighted Average with NumPy | by why amit | Medium
February 9, 2025 - How to handle it? To avoid this error, always ensure your weights are meaningful and their sum is greater than zero.
🌐
YouTube
youtube.com › watch
numpy weighted sum - YouTube
Download 1M+ code from https://codegive.com **understanding numpy weighted sum: a comprehensive overview**numpy, a powerful library in python, is widely rec...
Published: November 16, 2024
🌐
LabEx
labex.io › tutorials › python-how-to-implement-weighted-calculations-431443
How to implement weighted calculations | LabEx
import numpy as np def numpy_weighted_average(values, weights): """ Calculate weighted average using NumPy """ return np.average(values, weights=weights) ## Example usage data = np.array([85, 92, 78]) weights = np.array([0.3, 0.4, 0.3]) result = numpy_weighted_average(data, weights) print(f"NumPy Weighted Average: {result}") Pandas offers advanced weighted calculation methods: import pandas as pd def pandas_weighted_calculation(dataframe): """ Perform weighted calculations on DataFrame """ return dataframe.mul(dataframe['weight'], axis=0).sum() / dataframe['weight'].sum() ## Example DataFrame df = pd.DataFrame({ 'value': [85, 92, 78], 'weight': [0.3, 0.4, 0.3] }) result = pandas_weighted_calculation(df) print(f"Pandas Weighted Result: {result}")
Top answer
1 of 2
3

The method numpy.einsum is convenient for this:

np.einsum('ij,kli->klj', A, B)

The notation says: multiply A[i, j] by B[k, l, i] and sum over i; place the result in the cell [k, l, j].

Example:

A = np.array([(255, 0, 0), (0, 255, 0), (0, 0, 255)])
B = np.array([[[0.2, 0.6, 0.20], [0.2, 0.2, 0.60]], [[0.4, 0.4, 0.2], [0.3, 0.3, 0.4]]])
Y = np.einsum('ij,kli->klj', A, B)

Then Y is

array([[[  51. ,  153. ,   51. ],
        [  51. ,   51. ,  153. ]],

       [[ 102. ,  102. ,   51. ],
        [  76.5,   76.5,  102. ]]])
2 of 2
2

You are sum-reducing the first axis from A against the third from B, while the rest of the axes are spread out. This is a perfect setup to leverage BLAS based matrix-multiplication for tensors - np.tensordot, like so -

C = np.tensordot(B,A,axes=((2),(0)))

Related post to understand tensordot.

We can also manually reshape to 2D and use the matrix-multiplication for 2D : np.dot, like so -

B.reshape(-1,n).dot(A).reshape(x,y,3)

Note that B.dot(A) works as well, but that would be slower, most probably as it would loop through the first axis of B, while performing 2D matrix-multiplications for each 2D slice off it against A.

Runtime test -

In [180]: np.random.seed(0)
     ...: x,y,n = 100,100,100
     ...: A = np.random.rand(n,3)
     ...: B = np.random.rand(x,y,n)

# @Crazy Ivan's soln
In [181]: %timeit np.einsum('ij,kli->klj', A, B)
100 loops, best of 3: 4.21 ms per loop

In [182]: %timeit np.tensordot(B,A,axes=((2),(0)))
1000 loops, best of 3: 1.72 ms per loop

In [183]: np.random.seed(0)
     ...: x,y,n = 200,200,200
     ...: A = np.random.rand(n,3)
     ...: B = np.random.rand(x,y,n)

# @Crazy Ivan's soln
In [184]: %timeit np.einsum('ij,kli->klj', A, B)
10 loops, best of 3: 33.2 ms per loop

In [185]: %timeit np.tensordot(B,A,axes=((2),(0)))
100 loops, best of 3: 15.3 ms per loop
🌐
TutorialsPoint
tutorialspoint.com › compute-the-weighted-average-of-a-given-numpy-array
NumPy average() Function
August 9, 2023 - The NumPy average() function computes the weighted average or mean of the elements in an array along a specified axis. The weighted average allows for each element to have its own weight, which can modify the contribution of each element to ...