在python中更新双重分组的列

时间:2019-05-15 10:41:15

标签: python-3.x group-by

你好,我有一个DF,它一旦聚合起来就像这样:

DF_agg

   prime_broker_id    country_name  notional_current  carry_dt
0           BARCAP         AUSTRIA      2.616735e+07       271
1           BARCAP         BELGIUM      6.327196e+07       488
2           BARCAP         DENMARK      1.286309e+07        83
3           BARCAP         FINLAND      4.181843e+07       368
4           BARCAP          FRANCE      1.579292e+08      1813
5           BARCAP         GERMANY      2.653451e+08      2301
6           BARCAP         IRELAND      1.037968e+07       177

现在,我想通过添加新列DF_agg来更新此DF_agg['carry_rate']。新列是如下所示的计算结果:

DF.groupby(['prime_broker_id', 'country_name'], as_index=False).apply(
            lambda group: dollar_wtd_two(group, kw_param='carry_rate', kw_param2='notional_current'))

输出为:

prime_broker_id  country_name  
BARCAP           AUSTRIA            25.009402
                 BELGIUM            25.083404
                 DENMARK            25.000000
                 FINLAND            25.034493
                 FRANCE             25.000000
                 GERMANY            25.007943
                 IRELAND            25.000000
                 ISRAEL            399.242997

当我尝试更新

DF_agg['carry_rate'] = DF.groupby(['prime_broker_id', 'country_name'], as_index=False).apply(lambda group: dollar_wtd_two(group, kw_param='carry_rate', kw_param2='notional_current'))

dollar_wtd_two是我创建的一个函数,该函数基本上以美元的权重携带进来的汇率

过去,当我按一列进行聚合时,此代码行运行良好,但是当我按两列进行聚合时,代码失败:

TypeError: incompatible index of inserted column with frame index

我知道问题出在哪里,但我不知道如何解决。

非常感谢您的帮助

++++

这是一个无效的试用

DF.groupby(['prime_broker_id', 'country_name'], as_index=False).agg({"notional_current": np.sum,  "carry_rate": lambda group: dollar_wtd_two(group,'carry_rate', 'notional_current') }) 

0 个答案:

没有答案