[英]Pandas Resampling: TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
[英]pandas cannot group by date, Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but
您好,我有以下代码:
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
退货
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
但是当我尝试使用以下代码按月分组时:
df['Start date'].groupby(pd.Grouper(freq='M'))
或者
df.groupby(pd.Grouper(freq='M'))
我收到以下错误:
TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex'
我该如何解决这个问题?
谢谢。
尝试:
df.groupby(df['Start date'].dt.month_name().rename('month'))
如果您的索引不是日期时间类型,则需要使用pd.Grouper
设置键:
df.groupby(pd.Grouper(key="Start date", freq='M'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.