繁体   English   中英

dataframe 的行乘以另一个 dataframe 的列

[英]Rows of dataframe times column of another dataframe

我试图获得每个人的每种产品的加权平均值。 所以对于汤姆来说,它应该有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) 

我试过pd.DataFrame.multiply(df, df2, axis = 1) ,但我得到的所有值都是 NaN 。

对齐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

类似问题在这里: How to compute weighted sum of all elements in a row in pandas?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM