按sumproduct分组

时间:2019-02-03 19:20:17

标签: python pandas group-by apply loc

我正在使用具有以下结构的df:

df = DataFrame({'Date' : ['1', '1', '1', '1'],
            'Ref' : ['one', 'one', 'two', 'two'],
            'Price' : ['50', '65', '30', '35'],
            'MktPrice' : ['63', '63', '32', '32'],
            'Quantity' : ['10', '15', '20', '10'],
            'MarketQuantity': ['50', '50', '100', '100'],
            'Weightings' : ['2', '2', '4', '4'],
            'QxWeightings' : ['20', '30', '80', '40'],
            'MktQxWeightings': ['100', '100', '400', '400'],
            })   

当价格高于Mkt价格(并按日期和参考显示)时,我设法从MarketQuantity中获取代表我数量的加权百分比

def percentage(x):
    return (x.loc[x['Price'] >= x['MktPrice'], ['QxWeightings']].sum()/(x['MktQxWeightings'].sum()/len(x)))

df.groupby(['Date', 'Ref']).apply(percentage)

Date  Ref   Output 
1     one   0.3
1     two   0.1

但是,当我尝试仅按日期对它进行分组时,我得到:

Date  Output 
1     0.4

是先前输出的总和,当它应为0.14(30 + 40)/(100 + 400)时。

我该如何使用groupby? 提前非常感谢

1 个答案:

答案 0 :(得分:1)

IIUC,可能是这样的:

def percentage(x):
    return (x.loc[x['Price'] >= x['MktPrice'], ['QxWeightings']].sum()/(x['MktQxWeightings'].sum()/len(x)))

df_new=df.groupby(['Date', 'Ref','MktQxWeightings']).apply(percentage).reset_index()
print(df_new)

  Date  Ref  MktQxWeightings  QxWeightings
0    1  one              100           0.3
1    1  two              400           0.1

df_new.groupby('Date')['MktQxWeightings','QxWeightings'].apply(lambda x: x['QxWeightings'].\
                                                           cumsum().sum()*100/x['MktQxWeightings'].sum())

Date
1    0.14