[英]Rows of dataframe times column of another dataframe
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.所以对于汤姆来说,它应该有20x1.0+19x2.0+10x3.0,我也希望每个产品都有权重*产品。
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.我试过pd.DataFrame.multiply(df, df2, axis = 1)
,但我得到的所有值都是 NaN 。
Aligning the index in df2
will solve your problem.对齐df2
中的索引将解决您的问题。 And referencing the weights column in df2.并引用 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?类似问题在这里: How to compute weighted sum of all elements in a row in pandas?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.