Pandas groupby causing keyerror

I try to convert monthly time series data quarterly, and then summarize the amounts for the quarter. I get KeyError: 'date' when I run the following.

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 to use groupby in the origin and date fields? Is there a way to group without resetting the index?

abc= abc.set_index('date').to_period('Q').reset_index().groupby(['origin', 
'date']).agg(sum)
+4
source share
1 answer

Because when you do:

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

You have changed the "date" to the index.

Later you will try to access the “date” in the form of a column that no longer exists, so an error. reset_index operation restores the “date” as a column so that it works again.

"" , , :

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

Source: https://habr.com/ru/post/1676879/


All Articles