pandas groupby导致keyerror

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43904863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 03:35:13  来源:igfitidea点击:

pandas groupby causing keyerror

pandas

提问by oammon

I'm trying transform monthly time series data to quarterly then aggregate sums per quarter. I get a KeyError: 'date' when I run the following.

我正在尝试将月度时间序列数据转换为季度,然后每季度汇总总和。运行以下命令时出现 KeyError: 'date' 。

abc= abc.set_index('date').to_period('Q').groupby(['origin', 
'date']).agg(sum)

However, when I reset the index as shown below, the code works. Why do I need to reset the index in order to use groupby on the origin and date fields? Is there a way to group without resetting the index?

但是,当我如下所示重置索引时,代码有效。为什么我需要重置索引才能在原点和日期字段上使用 groupby?有没有办法在不重置索引的情况下分组?

abc= abc.set_index('date').to_period('Q').reset_index().groupby(['origin', 
'date']).agg(sum)

采纳答案by Allen

Because when you do:

因为当你这样做时:

abc= abc.set_index('date').to_period('Q')

You've changed 'date' to a index.

您已将“日期”更改为索引。

Later you try to access 'date' as a column which doesn't exist any more, hence the error. a reset_index operation restores 'date' as a column so it works again.

稍后您尝试将“日期”作为不再存在的列访问,因此出现错误。reset_index 操作将“日期”恢复为一列,以便它再次工作。

You can retain 'date' as column while setting it as index by doing:

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

abc= abc.set_index('date', drop=False).to_period('Q').groupby(['origin', 
'date']).agg(sum)