我有一个数据帧,
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
Run Code Online (Sandbox Code Playgroud)
我需要一个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
Run Code Online (Sandbox Code Playgroud)
groupby或任何其他解决方案是否可能相同?
jrj*_*rjc 75
要将多个函数传递给groupby对象,需要传递一个字典,其中包含与列对应的聚合函数:
# Define a lambda function to compute the weighted mean:
wm = lambda x: np.average(x, weights=df.loc[x.index, "adjusted_lots"])
# Define a dictionary with the functions to apply for a given column:
f = {'adjusted_lots': ['sum'], 'price': {'weighted_mean' : wm} }
# Groupby and aggregate with your dictionary:
df.groupby(["contract", "month", "year", "buys"]).agg(f)
adjusted_lots price
sum weighted_mean
contract month year buys
C Z 5 Sell -19 424.828947
CC U 5 Buy 5 3328.000000
SB V 5 Buy 12 11.637500
W Z 5 Sell -5 554.850000
Run Code Online (Sandbox Code Playgroud)
你可以在这里看到更多:
在这里类似的问题:
希望这可以帮助
使用聚合函数字典的解决方案将在熊猫的未来版本(0.22 版)中被弃用:
FutureWarning: using a dict with renaming is deprecated and will be removed in a future
version return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
使用 groupby 应用并返回一个系列来重命名列,如: 重命名 Pandas 聚合中的结果列(“FutureWarning:不推荐使用重命名的字典”)
def my_agg(x):
names = {'weighted_ave_price': (x['adjusted_lots'] * x['price']).sum()/x['adjusted_lots'].sum()}
return pd.Series(names, index=['weighted_ave_price'])
Run Code Online (Sandbox Code Playgroud)
产生相同的结果:
>df.groupby(["contract", "month", "year", "buys"]).apply(my_agg)
weighted_ave_price
contract month year buys
C Z 5 Sell 424.828947
CC U 5 Buy 3328.000000
SB V 5 Buy 11.637500
W Z 5 Sell 554.850000
Run Code Online (Sandbox Code Playgroud)
用groupby(...)。apply(...)进行加权平均可能会很慢(以下内容为100倍)。在此主题中查看我的答案(和其他答案)。
def weighted_average(df,data_col,weight_col,by_col):
df['_data_times_weight'] = df[data_col]*df[weight_col]
df['_weight_where_notnull'] = df[weight_col]*pd.notnull(df[data_col])
g = df.groupby(by_col)
result = g['_data_times_weight'].sum() / g['_weight_where_notnull'].sum()
del df['_data_times_weight'], df['_weight_where_notnull']
return result
Run Code Online (Sandbox Code Playgroud)
小智 5
这样做会不会简单得多。
| 归档时间: |
|
| 查看次数: |
32327 次 |
| 最近记录: |