[英]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.