我有一个数据框
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
我需要一个调整后的价格总和,价格是加权平均,价格和未调整的价格,按所有其他列分组,即按(合同、月份、年份和购买)分组
类似的R解决方案是通过以下代码实现的,使用dplyr,但是在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或任何其他解决方案是否也有可能?
按groupby(…)进行加权平均。apply(…)可能非常慢(从下面的100倍)。 在this thread上看到我的答案(和其他人)。
在将来的pandas版本(0.22版)中将不推荐使用使用dict聚合函数的解决方案:
使用groupby apply并返回一个序列来重命名列,如中所述: Rename result columns from Pandas aggregation ("FutureWarning: using a dict with renaming is deprecated")
产生相同的结果:
要将多个函数传递给groupby对象,需要传递一个字典,其中包含与列对应的聚合函数:
你可以在这里看到更多:
还有一个类似的问题:
希望这有帮助
相关问题 更多 >
编程相关推荐