如何解决使用 groupby 按天对 OHLC 数据进行分组
因为key
参数是列名,你可以省略它:
table = df.groupby(pd.Grouper(freq='1D'))
或使用level
参数:
table = df.groupby(pd.Grouper(level='index', freq='1D'))
或转换index
为列(在我看来过于复杂):
table = df.reset_index().groupby(pd.Grouper(key='index', freq='1D'))
解决方法
我正在将 sqlite db 中的分钟数据读取到索引是 datetime 对象的数据框中:
open high low close volume trade_count vwap ticker
index
2022-09-13 04:26:00+00:00 163.50 163.50 163.50 163.50 298.0 12.0 163.503255 AAPL
2022-09-13 04:45:00+00:00 163.50 163.50 163.50 163.50 727.0 1.0 163.500000 AAPL
2022-09-13 05:16:00+00:00 163.43 163.43 163.43 163.43 202.0 4.0 163.430000 AAPL
2022-09-13 05:44:00+00:00 163.50 163.50 163.50 163.50 121.0 2.0 163.499587 AAPL
2022-09-13 05:45:00+00:00 163.46 163.46 163.46 163.46 200.0 2.0 163.460000 AAPL
... ... ... ... ... ... ... ... ...
2022-09-14 19:57:00+00:00 99.73 99.73 99.69 99.69 1273.0 18.0 99.693425 ZROZ
2022-09-14 19:58:00+00:00 99.69 99.69 99.66 99.69 1114.0 11.0 99.686965 ZROZ
2022-09-14 19:59:00+00:00 99.69 99.82 99.69 99.76 9764.0 76.0 99.736332 ZROZ
2022-09-14 20:00:00+00:00 99.76 99.76 99.76 99.76 2168.0 1.0 99.760000 ZROZ
2022-09-14 20:33:00+00:00 99.96 99.96 99.96 99.96 150.0 4.0 99.968667 ZROZ
[317028 rows x 8 columns] df
我想将这个庞大的数据帧分成几位,按股票代码和日期分组。当我尝试以下方法时:
table = df.groupby(pd.Grouper(key='index',freq='1D'))
我得到错误:
raise KeyError(f"The grouper name {key} is not found")
KeyError: 'The grouper name index is not found'
当我将密钥更改为:
table = df.groupby(pd.Grouper(key=df.index,freq='1D'))
我得到错误:
if getattr(self._gpr_index,"name",None) == key and isinstance(
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
如何按股票代码和日期分组?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。