xzt
xzt

Reputation: 111

how to group by added columns in python

Previously, I was able to read an excel file to python as a df which contains a column called date in the format like 2011-02-01, and I wanted to get the quarter of each date and group by the data in quarter. I have added a column to the df called quarter, but when I tried

df.groupby('quarter')

it showed me that

No axis named quarter for object type class'pandas.core.frame.DataFrame' 

Is it possible to do the thing I wanted? Or is there any other way to do that?

Upvotes: 0

Views: 83

Answers (1)

IanS
IanS

Reputation: 16251

Jarad's answer (in the comments) is very good, but here is another option, which avoids creating a new column:

df.groupby(pd.TimeGrouper(key='Date', freq='Q'))

This option is also more flexible. It can be used to group by non-standard periods, e.g. two weeks:

df.groupby(pd.TimeGrouper(key='Date', freq='2W'))

Upvotes: 2

Related Questions