Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

pandas cannot group by date, Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but

Hello I have the following code:

import pandas as pd
df = pd.read_csv('https://assets.datacamp.com/production/repositories/3551/datasets/181c142c56d3b83112dfc16fbd933fd995e80f94/capital-onebike.csv',
                 parse_dates = ['Start date', 'End date'])
df.dtypes

Return this

Start date              datetime64[ns]
End date                datetime64[ns]
Start station number             int64
Start station                   object
End station number               int64
End station                     object
Bike number                     object
Member type                     object
dtype: object

But when I try to group by month with the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 df['Start date'].groupby(pd.Grouper(freq='M'))

or

 df.groupby(pd.Grouper(freq='M'))

I got the following error:

TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'

How can I solve this?

Thanks.

>Solution :

with pd.Grouper you need to set the key, if your index is a datetime type:

df.groupby(pd.Grouper(key="Start date", freq='M'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading