尝试将多个功能聚合到新列时出现意外的KeyError Pandas [英] Unexpected KeyError Pandas while trying to aggregate multiple functions into new column

查看:146
本文介绍了尝试将多个功能聚合到新列时出现意外的KeyError Pandas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了以下问题:

将多个函数应用于多个groupby列

我有

                    p.date p.instrument                p.sector  \
11372  2013-02-15 00:00:00            A             Health Care   
11373  2013-02-15 00:00:00           AA               Materials   
11374  2013-02-15 00:00:00         AAPL  Information Technology   
11375  2013-02-15 00:00:00         ABBV             Health Care   
11376  2013-02-15 00:00:00          ABC             Health Care   

                                p.industry    p.retn  p.pfwt     b.bwt  
11372     Health Care Equipment & Services -5.232929     NaN  0.000832  
11373                             Aluminum  0.328947     NaN  0.000907  
11374                    Computer Hardware -1.373927     NaN  0.031137  
11375                      Pharmaceuticals  2.756020     NaN  0.004738  
11376  Health Care Distribution & Services -0.371179     NaN  0.000859 

但是当我尝试:

test1.groupby("p.sector").agg({'r1': lambda x: x['p.pfwt'].sum()})

我得到了错误

KeyError: 'r1'

我正在尝试使用来自当前DataFrame的一组结果创建新列.

I'm trying to create new columns with a set of results from the current DataFrame.

我想念什么?谢谢

推荐答案

使用

test1.groupby("p.sector").agg({'p.pfwt': np.sum})

请参见此熊猫文档.

  • 聚合字典中的关键字必须与数据框中的现有关键字相对应.您的程序失败,因为数据框中没有'r1'列,因此它无法聚合不存在的内容.
  • 如果需要重命名结果,则可以为以下系列添加链式操作:.agg([np.sum, np.mean, np.std]).rename(columns={'sum': 'foo', 'mean': 'bar', 'std': 'baz'}) )

这篇关于尝试将多个功能聚合到新列时出现意外的KeyError Pandas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆