python - 尝试将多个函数聚合到新列时出现意外的 KeyError Pandas

标签 python pandas dictionary dataframe aggregate

我看过以下问题:

Apply multiple functions to multiple groupby columns

我有数据

                    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 的一组结果创建新列。

我错过了什么?谢谢

最佳答案

使用

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

参见 this pandas docs例如。

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

关于python - 尝试将多个函数聚合到新列时出现意外的 KeyError Pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27076792/

相关文章:

python - 从Python中的列表的字典创建字典的字典

python - 使用 pandas 找到矩阵中的负对

python - 按第二列排序的列中每组的 cumsum 追加到原始数据框

python - 获取随 secret 钥 :value pairs from dictionary in python

Python 3 : How to sum results into a dictionary

python - 使用 Django 按值进行多字段 bool 过滤

python - 仅从 s3 存储桶文件夹中获取文件名

javascript - 在js中如何使用Map、Reduce和filter将华氏度转换为摄氏度

java - 如何使用 mac os9 行终止符生成文件?

python Pandas : How do I get data one for each nth line with CSV files in?