【发布时间】:2023-03-28 06:45:01
【问题描述】:
我看过以下问题:
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 的一组结果创建新列。
我错过了什么?谢谢
【问题讨论】:
-
聚合字典中的键必须与数据帧中预先存在的键相对应。您的数据框中没有“r1”列,因此您无法汇总不存在的内容
标签: python pandas dictionary dataframe aggregate