pandas groupby导致keyerror

oam*_*mon 5 pandas

我正在尝试将每月时间序列数据转换为季度,然后每季度汇总总和.当我运行以下内容时,我得到一个KeyError:'date'.

abc= abc.set_index('date').to_period('Q').groupby(['origin', 
'date']).agg(sum)
Run Code Online (Sandbox Code Playgroud)

但是,当我重置索引,如下所示,代码工作.为什么我需要重置索引才能在origin和date字段中使用groupby?有没有办法在不重置索引的情况下进行分组?

abc= abc.set_index('date').to_period('Q').reset_index().groupby(['origin', 
'date']).agg(sum)
Run Code Online (Sandbox Code Playgroud)

All*_*len 5

因为当你这样做时:

abc= abc.set_index('date').to_period('Q')
Run Code Online (Sandbox Code Playgroud)

您已将"日期"更改为索引.

稍后您尝试将"日期"作为不再存在的列进行访问,从而导致错误.reset_index操作将'date'恢复为列,以便再次工作.

通过执行以下操作,您可以将'date'保留为列,同时将其设置为索引:

abc= abc.set_index('date', drop=False).to_period('Q').groupby(['origin', 
'date']).agg(sum)
Run Code Online (Sandbox Code Playgroud)