I tried to get the weighted average of each product for each person. So for Tom, it should have 20x1.0+19x2.0+10x3.0, I also hope to have the weights*product by each product as well.
data = {'Name':['Tom', 'nick', 'krish', 'jack'], '1stproducts':[20, 21, 19, 18], '2ndproduct': [19, 28, 10, 10],
'3rdproduct': [10, 18, 20, 30]}
df = pd.DataFrame(data)
weights = {"weights": [1.0, 2.0, 3.0]}
df2 = pd.DataFrame(weights)
I have tried pd.DataFrame.multiply(df, df2, axis = 1)
, but I got NaN for all values.
Aligning the index in df2
will solve your problem. And referencing the weights column in df2.
df2 = pd.DataFrame(weights, index=['1stproducts', '2ndproduct', '3rdproduct'])
In [26]: df[['1stproducts', '2ndproduct', '3rdproduct']] * df2.weights
Out[26]:
1stproducts 2ndproduct 3rdproduct
0 20.0 38.0 30.0
1 21.0 56.0 54.0
2 19.0 20.0 60.0
3 18.0 20.0 90.0
Similar question here: How to compute weighted sum of all elements in a row in pandas?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.