簡體   English   中英

pandas 不能按日期分組,僅對 DatetimeIndex、TimedeltaIndex 或 PeriodIndex 有效,但

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM