我正在将 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()
如何按股票代码和日期分组?
因为key参数是列名,你可以省略它:
key
table = df.groupby(pd.Grouper(freq='1D'))
或使用level参数:
level
table = df.groupby(pd.Grouper(level='index', freq='1D'))
或转换index为列(在我看来过于复杂):
index
table = df.reset_index().groupby(pd.Grouper(key='index', freq='1D'))