900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > pandas算加权平均值_python – groupby加权平均值和pandas数据帧中的和

pandas算加权平均值_python – groupby加权平均值和pandas数据帧中的和

时间:2022-10-27 08:43:59

相关推荐

pandas算加权平均值_python – groupby加权平均值和pandas数据帧中的和

我有一个数据帧,

Out[78]:

contract month year buys adjusted_lots price

0 W Z 5 Sell -5 554.85

1 C Z 5 Sell -3 424.50

2 C Z 5 Sell -2 424.00

3 C Z 5 Sell -2 423.75

4 C Z 5 Sell -3 423.50

5 C Z 5 Sell -2 425.50

6 C Z 5 Sell -3 425.25

7 C Z 5 Sell -2 426.00

8 C Z 5 Sell -2 426.75

9 CC U 5 Buy 5 3328.00

10 SB V 5 Buy 5 11.65

11 SB V 5 Buy 5 11.64

12 SB V 5 Buy 2 11.60

我需要一个adjust_lots的总和,价格是加权平均值,价格和ajusted_lots,按所有其他列分组,即.按(合同,月份,年份和购买)分组

使用dplyr通过以下代码实现对R的类似解决方案,但无法在pandas中执行相同操作.

> newdf = df %>%

select ( contract , month , year , buys , adjusted_lots , price ) %>%

group_by( contract , month , year , buys) %>%

summarise(qty = sum( adjusted_lots) , avgpx = weighted.mean(x = price , w = adjusted_lots) , comdty = "Comdty" )

> newdf

Source: local data frame [4 x 6]

contract month year comdty qty avgpx

1 C Z 5 Comdty -19 424.8289

2 CC U 5 Comdty 5 3328.0000

3 SB V 5 Comdty 12 11.6375

4 W Z 5 Comdty -5 554.8500

groupby或任何其他解决方案是否可能相同?

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。