【发布时间】:2021-01-11 22:53:38
【问题描述】:
我有一个这样的数据框:
部门、名称、日期、价格
我想汇总我的数据,以便计算 3 年的波动率:
result = (df
.groupby(['sector', 'name'])
volat_3Y=('price', lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var())) )
我还想计算 2020 年、2019 年...的性能,但是当我尝试时:
result = (df
.groupby(['sector', 'name'])
volat_3Y=('price', lambda x: 100*np.sqrt(252*np.log(x[-3*252:-1] / x[-3*252:-1].shift(1)).var()))
perf_2020=('price', lambda x.loc['2020-09-18']) # Just to have access to a specific date
)
我有一条错误消息。有什么建议吗?
这是错误信息:
KeyError Traceback(最近一次调用最后一次) pandas._libs.index.DatetimeEngine.get_loc() 中的 pandas/_libs/index.pyx
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()
密钥错误:1600387200000000000
在处理上述异常的过程中,又发生了一个异常:
KeyError Traceback(最近一次调用最后一次) ~/opt/anaconda3/envs/Data/lib/python3.8/site-packages/pandas/core/indexes/base.py in get_loc(self、key、method、tolerance) 2888 尝试: -> 2889 返回 self._engine.get_loc(casted_key) 2890 除了 KeyError 错误:
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.DatetimeEngine.get_loc()
KeyError: Timestamp('2020-09-18 00:00:00')
【问题讨论】:
-
我有一条错误消息,你为什么不把错误贴在这里?
-
当我在一个组内做同样的事情时,我会添加:group.get_group(('sect1', 'nom1')).agg(perf_2020=('VL', lambda x: 100 *x.loc['2020-09-18'])) 我有一个数字:price perf_2020 10458.0