pandas数据的加权平均和分组

2024-04-23 13:54:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据框

    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或任何其他解决方案是否也有可能?


Tags: 价格buy解决方案yearpricesbcccontract
3条回答

按groupby(…)进行加权平均。apply(…)可能非常慢(从下面的100倍)。 在this thread上看到我的答案(和其他人)。

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

在将来的pandas版本(0.22版)中将不推荐使用使用dict聚合函数的解决方案:

FutureWarning: using a dict with renaming is deprecated and will be removed in a future 
version return super(DataFrameGroupBy, self).aggregate(arg, *args, **kwargs)

使用groupby apply并返回一个序列来重命名列,如中所述: Rename result columns from Pandas aggregation ("FutureWarning: using a dict with renaming is deprecated")

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'])

产生相同的结果:

>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

要将多个函数传递给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

你可以在这里看到更多:

还有一个类似的问题:

希望这有帮助

相关问题 更多 >