Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others


0 votes
in Technique[技术] by (71.8m points)

python - Multiply list of arrays by list of scalars and sum elements

I have a list of arrays (factors) that I want to first multiply by a list of scalars (weights) and then sum the elements of the product of each array. I have tried the following but I get an error. Any suggestion would be highly appreciated.

factors = np.array([[f1], [f2], [f3]])
weights = np.array([0.333, 0.333, 0.333])
prod = np.sum(factors.transpose()*weights)

Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Consider the following inputs

factors = np.array([[1, 2], [3, 4], [5, 6]])
weights = np.array([[2, 1, 0]]) # notice how this is a 2d array

First convert weights into a 2D "Vector" so that you can multiply each term

weights = weights.T # [[2], [1], [0]]

Then you can just simply multiply by using the __mul__ dunder

new_factors = weights * factors # [[2, 4],[3, 4],[0, 0]]

Then you can just use np.array.sum to sum each row


The output is

array([6, 7, 0])

Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share