我有两个数据-一个在每个组下的值。第二种数据对每一组都有权重,以获得加权平均值。
df1 =
product group1 group2 group3 group4 group5
xyz 223056 907858 4803 586623 835423
abc 557042 382306 915624 786236 413817
pqr 951348 723503 587397 141975 567826df2 =
group weight
group1 0.5
group2 7.5
group3 10
group4 1.5
group5 50我想得到每个产品的所有组的加权平均值,并将其附加到df1中。例如:
product group1 group2 group3 group4 group5 weighted-average
xyz 223056 907858 4803 586623 835423 40
abc 557042 382306 915624 786236 413817 25
pqr 951348 723503 587397 141975 567826 30有什么简单的方法吗?我在excel上成功地做到了这一点,但我想在熊猫身上尝试,因为我还在学习它。
发布于 2022-10-21 11:03:14
对于相同的顺序列和索引,使用np.average和DataFrame.reindex:
s = df2.set_index('group')['weight']
df1['wa'] = np.average(df1.reindex(columns=s.index), weights=s, axis=1)
print (df1)
product group1 group2 group3 group4 group5 wa
0 xyz 223056 907858 4803 586623 835423 713950.755396
1 abc 557042 382306 915624 786236 413817 491687.194245
2 pqr 951348 723503 587397 141975 567826 581009.769784如果总是使用相同的顺序,可以使用:
df1 = df1.set_index('product')
df1['wa'] = np.average(df1, weights=df2['weight'], axis=1)
print (df1)
group1 group2 group3 group4 group5 wa
product
xyz 223056 907858 4803 586623 835423 713950.755396
abc 557042 382306 915624 786236 413817 491687.194245
pqr 951348 723503 587397 141975 567826 581009.769784发布于 2022-10-21 11:07:40
您可以将multiply按权重,sum和divide按权重之和计算:
df1['wa'] = (df1.mul(df2.set_index('group')['weight'])
.sum(axis=1).div(df2['weight'].sum())
)产出:
product group1 group2 group3 group4 group5 wa
0 xyz 223056 907858 4803 586623 835423 713950.755396
1 abc 557042 382306 915624 786236 413817 491687.194245
2 pqr 951348 723503 587397 141975 567826 581009.769784https://stackoverflow.com/questions/74152420
复制相似问题